<?php

namespace Opentalent\OtTemplating\XClass\Form\Configuration;

use Opentalent\OtCore\Exception\NoSuchWebsiteException;
use Opentalent\OtCore\Website\OtPageRepository;
use Opentalent\OtCore\Website\OtWebsiteRepository;
use Opentalent\OtTemplating\Templating\TemplateRepository;
use Psr\Container\ContainerInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\Exception;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Form\Mvc\Configuration\Exception\ExtensionNameRequiredException;

class ConfigurationManager extends \TYPO3\CMS\Form\Mvc\Configuration\ConfigurationManager
{
    private OtWebsiteRepository $otWebsiteRepository;
    private OtPageRepository $otPageRepository;

    /**
     * @param OtWebsiteRepository $otWebsiteRepository
     * @return void
     */
    public function injectOtWebsiteRepository(OtWebsiteRepository $otWebsiteRepository): void
    {
        $this->otWebsiteRepository = $otWebsiteRepository;
    }

    /**
     * @param OtPageRepository $otPageRepository
     * @return void
     */
    public function injectOtPageRepository(OtPageRepository $otPageRepository): void
    {
        $this->otPageRepository = $otPageRepository;
    }

    /**
     * Override the default form configuration loader to add the forms directory matching
     * the current be user mounted organization(s) id(s)
     *
     * @param string $extensionName
     * @return array
     * @throws ExtensionNameRequiredException
     * @throws NoSuchWebsiteException
     * @throws Exception
     */
    protected function getConfigurationFromYamlFile(string $extensionName): array
    {
        $settings = parent::getConfigurationFromYamlFile($extensionName);

        if ($this->getContentObject()->data === null) {
            $this->getContentObject()->data = ['uid' => 1];
        }

        foreach ($this->otPageRepository->getCurrentBeUserMountpoints() as $rootUid) {

            $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);

            if ($website['organization_id']) {
                $settings['persistenceManager']['allowedFileMounts'][] = '1:/form_definitions/' . $website['organization_id'] . '/';
            }
        }

        return $settings;
    }
}
