<?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;

    protected Utilities $utilities;

    protected  ActivePageRepository $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'
            ],
            'expiredlast30' => [
                'controller' => 'Backend',
                'action' => 'showLast30Days',
                'label' => 'Beiträge, die in den letzten 30 Tagen ausgelaufen sind'
            ],
            'expiredlast90' => [
                'controller' => 'Backend',
                'action' => 'showLast90Days',
                'label' => 'Beiträge, die in den letzten 90 Tagen ausgelaufen sind'
            ],
        ];

        $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 $menuItemConfig) {
            $isActive = false;
            if ($this->request->getControllerName() === $menuItemConfig['controller']) {
                if ($this->request->getControllerActionName() === $menuItemConfig['action']) {
                    $isActive = true;
                }
            }

            $menuItem = $menu->makeMenuItem()
                ->setTitle($menuItemConfig['label'])
                ->setHref($this->getHref($menuItemConfig['controller'], $menuItemConfig['action']))
                ->setActive($isActive);
            $menu->addMenuItem($menuItem);
        }
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($menu);
    }

    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
    {
        $this->utilities = GeneralUtility::makeInstance(Utilities::class);
        $activePages = $this->activePageRepository->findActivePagesAndPageCreatetors();
        $itemsperpage = $this->settings['itemsPerPage'] ?? 50;

        $pageObjectArray = $this->createPageObjectsFromArrayData($activePages);

        $currentPage = $this->request->hasArgument('currentPage') ? $this->request->getArgument('currentPage') : 1;

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

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

    public function showLast30DaysAction()
    {
        $activePagesExpiredInLast30days = $this->activePageRepository->findExpiredRecordsInTheLast30OR90Days(30);
        $itemsPerPage = $this->settings['itemsPerPage'] ?? 50;

        $pageObjectArray = $this->createPageObjectsFromArrayData($activePagesExpiredInLast30days);

        $currentPage = $this->request->hasArgument('currentPage') ? $this->request->getArgument('currentPage') : 1;

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

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

    public function showLast90DaysAction()
    {
        //$this->utilities = GeneralUtility::makeInstance(Utilities::class);
        $activePagesExpiredInLast90days = $this->activePageRepository->findExpiredRecordsInTheLast30OR90Days(90);
        $itemsPerPage = $this->settings['itemsPerPage'] ?? 50;

        $pageObjectArray = $this->createPageObjectsFromArrayData($activePagesExpiredInLast90days);


        $currentPage = $this->request->hasArgument('currentPage') ? $this->request->getArgument('currentPage') : 1;

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

        $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();
        $actionName = '';

        switch($controllerActionName) {
            case 'index':
                $actionName = 'index';
                break;
            case 'showLast30Days':
                $actionName = 'showLast30Days';
                break;
            case 'showLast90Days':
                $actionName = 'showLast90Days';
                break;
        }

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

    protected function createPageObjectsFromArrayData(array $data)
    {
        $pageObjectArray = [];
        $this->utilities = GeneralUtility::makeInstance(Utilities::class);

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

            $pageObjectArray[] = $pageObj;
        }
        return $pageObjectArray;

    }

}
