<?php

namespace Meramo\Pagemanager\Controller;

use Meramo\Pagemanager\Domain\Model\ActivePage;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use Meramo\Pagemanager\Domain\Repository\ActivePageRepository;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use TYPO3\CMS\Core\Pagination\ArrayPaginator;
use TYPO3\CMS\Core\Pagination\SimplePagination;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
use Meramo\Pagemanager\Utils\Utilities;

class BackendController extends ActionController
{
    protected ModuleTemplateFactory $moduleTemplateFactory;
    protected ModuleTemplate $moduleTemplate;
    protected PageRenderer $pageRenderer;

    /**
     * @var activePageRepository
     */
    protected $activePageRepository;

    public function __construct(
        ActivePageRepository $activePageRepository
    ) {
        $this->activePageRepository = $activePageRepository;
    }

    protected function initializeView(ViewInterface $view)
    {
        $menuItems = [
            'index' => [
                'controller' => 'Backend',
                'action' => 'index',
                'label' => 'Heute oder demnächst auslaufende Beiträge',
                'parameters' => ['daysPast' => 0]
            ],
            'expiredlast30' => [
                'controller' => 'Backend',
                'action' => 'showLast',
                'label' => 'Beiträge, die in den letzten 30 Tagen ausgelaufen sind',
                'parameters' => ['daysPast' => 30]
            ],
            'expiredlast90' => [
                'controller' => 'Backend',
                'action' => 'showLast',
                'label' => 'Beiträge, die in den letzten 90 Tagen ausgelaufen sind',
                'parameters' => ['daysPast' => 90]
            ],
        ];

        $this->moduleTemplateFactory = GeneralUtility::makeInstance(ModuleTemplateFactory::class);
        $this->moduleTemplate = $this->moduleTemplateFactory->create($this->request);

        $menu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
        $menu->setIdentifier('PageManagerModuleMenu');

        foreach ($menuItems as $key => $menuItemConfig) {
            $isActive = false;
            if ($this->request->getControllerName() === $menuItemConfig['controller']) {
                if ($this->request->getControllerActionName() === $menuItemConfig['action']) {
                    $queryParams = $this->request->getQueryParams();
                    if (!isset($menuItemConfig['parameters']['daysPast']) ||
                        (isset($queryParams['tx_pagemanager_tools_pagemanagerpgmgt']['daysPast']) &&
                            $queryParams['tx_pagemanager_tools_pagemanagerpgmgt']['daysPast'] == $menuItemConfig['parameters']['daysPast'])) {
                        $isActive = true;
                        $activeMenuItem = $key; // store the key of the active menu item
                        $view->assign('activeMenuItem', $activeMenuItem);
                    }
                }
            }
            $menuItem = $menu->makeMenuItem()
                ->setTitle($menuItemConfig['label'])
                ->setHref(
                    $this->getHref($menuItemConfig['controller'], $menuItemConfig['action'], $menuItemConfig['parameters'] ?? []))
                ->setActive($isActive);
            $menu->addMenuItem($menuItem);
        }
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($menu);
//        $view->assign('activeMenuItem', $activeMenuItem);
    }

    protected function translate($key, $arguments): string
    {
        return LocalizationUtility::translate(
            $key,
            'pagemanager',
            $arguments
        );
    }

    protected function getHref($controller, $action, $parameters = [])
    {
        $this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $this->uriBuilder->setRequest($this->request);

        return $this->uriBuilder->reset()->uriFor($action, $parameters, $controller);
    }

    public function indexAction(): ResponseInterface
    {
        $response = $this->displayPages(12, 0);
        return $response;
    }

    public function showLastAction(int $daysPast = 0)
    {
        $response = $this->displayPages(22, 1, $daysPast, 'DESC', true);
        return $response;
    }

    public function displayPages(int $redStatus, int $hiddenStatus, int $daysPast = 0, string $orderBy = 'ASC', bool $isExpired = false): ResponseInterface
    {
        $this->utilities = GeneralUtility::makeInstance(Utilities::class);
        $pages = $this->activePageRepository->findPages($redStatus, $hiddenStatus, $daysPast, $orderBy);
        $itemsperpage = $this->settings['itemsPerPage'] ?? 50;

        $pageObjectArray = [];

        foreach ($pages as $page) {
            $pageObj = new ActivePage();
            $pageObj->setUid($page['uid']);
            $pageObj->setStarttime($page['starttime']);
            $pageObj->setEndtime($page['endtime']);
            $pageObj->setTitle($page['title']);
            $pageObj->setRoof($page['roof']);
            $pageObj->setCategory($this->utilities->createCategoryFromSlug($page['slug']));
            $pageObj->setCreator($page['username']);
            $pageObj->setFullName($page['realName']);

            array_push($pageObjectArray, $pageObj);
        }
        $currentPage = $this->request->hasArgument('currentPage') ? $this->request->getArgument('currentPage') : 1;

        $this->buildPagination($pageObjectArray, $itemsperpage, $currentPage);

        if($isExpired) {
            $this->view->assign('daysPast',$daysPast);
        }

        $this->moduleTemplate->setContent($this->view->render());
        return $this->htmlResponse($this->moduleTemplate->renderContent());
    }


    /**
     * @param array $activePages
     * @param int $currentPage
     * @param int $itemsperpage
     *
     */
    protected function buildPagination(array $activePages, int $itemsperpage, int $currentPage = 1)
    {
        $arrayPaginator = new ArrayPaginator($activePages, $currentPage, $itemsperpage);
        $paging = new SimplePagination($arrayPaginator);
        $totalNumberOfRecords = count($activePages);

        $cPage = $arrayPaginator->getCurrentPageNumber();
        $controlleractionName = $this->request->getControllerActionName();
        $actioName = '';

        switch($controlleractionName) {
            case 'index':
                $actionName = 'index';
                break;
            case 'showLast':
                $actionName = 'showLast';
                break;
        }

        $this->view->assignMultiple(
            [
                'cpage' => $cPage,
                'totalRecords' => $totalNumberOfRecords,
                'activepages' => $activePages,
                'paginator' => $arrayPaginator,
                'paging' => $paging,
                'pages' => range(1, $paging->getLastPageNumber()),
                'actionName' => $actionName
            ]
        );
    }
}
