<?php

namespace Opentalent\OtTemplating\XClass\Form\Configuration;

use Opentalent\OtCore\Exception\NoSuchWebsiteException;
use Opentalent\OtCore\Website\OtPageRepository;
use Opentalent\OtCore\Website\OtWebsiteRepository;
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
{
    /**
     * 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);

        $otPageRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OtPageRepository::class);
        foreach ($otPageRepository->getCurrentBeUserMountpoints() as $rootUid) {

            $otWebsiteRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OtWebsiteRepository::class);
            $website = $otWebsiteRepository->getWebsiteByPageUid($rootUid);

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

        return $settings;
    }
}
