<?php

namespace Opentalent\OtCore\Controller;

use Opentalent\OtCore\Exception\NoSiteSelected;
use Opentalent\OtCore\Website\OtPageRepository;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * Base class for all controllers of backend modules that need
 * a typo3 site's page to be selected to execute **ALL** of its actions methods
 *
 * If no page is selected or if this page does not have any root page as an ancestor,
 * the action is forwarded to a page asking the user to select one.
 *
 * If only one website appears in the page-tree, this site is automatically selected
 *
 * Class BeOnSiteController
 */
class SelectedSiteController extends ActionController
{
    /**
     * The current site root page uid
     *
     * @var int
     */
    protected $currentRootUid;

    /** [FOR TESTS ONLY] */
    protected $preventPropagation = false;

    /**
     *
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
     */
    protected function callActionMethod() {

        // Check if the current be-user has a db_mountpoint, and only has one.
        // If so, this will be considered as the selected site (since its the only one available)
        $mountpoints = $this->otPageRepository->getCurrentBeUserMountpoints();

        if ($mountpoints && count($mountpoints) === 1) {
            $this->currentRootUid = (int)$mountpoints[0];
        } else {
            // No db mountpoint has been set up, or more than one.
            // Now we check if a site's page is selected
            try {
                if ($this->otPageRepository == null) {
                    $objectManager = new ObjectManager();
                    $this->otPageRepository = $objectManager->get(OtPageRepository::class);
                }
                $this->currentRootUid = $this->otPageRepository->getCurrentRootUid();
            } catch (NoSiteSelected $e) {
                $this->currentRootUid = null;
            }
        }

        // [TESTS ONLY]
        if ($this->preventPropagation) { return; }

        // No site is selected, redirect to the warning page
        if ($this->actionMethodName != 'displayNoSelectedPageWarningAction' && $this->currentRootUid == null) {
            $this->forward('displayNoSelectedPageWarning', 'SelectedSite', 'OtCore');
        }

        parent::callActionMethod();
    }

    protected function displayNoSelectedPageWarningAction() {}
}
