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

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'
      ],
      'expiredlast30' => [
        'controller' => 'Backend',
        'action' => 'showLast30',
        'label' => 'Beiträge, die in den letzten 30 Tagen ausgelaufen sind'
      ],
      'expiredlast90' => [
        'controller' => 'Backend',
        'action' => 'showLast90',
        '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->gedoens = GeneralUtility::makeInstance(Gedoens::class);
    $activePages = $this->activePageRepository->findActivePagesAndPageCreatetors();
    $itemsperpage = $this->settings['itemsPerPage'] ?? 50;

    $pageObjectArray = [];

    foreach ($activePages 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->gedoens->createCategoryFromSlug($activePage['slug']));
      $pageObj->setCreator($activePage['username']);
      $pageObj->setFullName($activePage['realName']);

      array_push($pageObjectArray, $pageObj);
    }
    $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 showLast30Action()
  {
      $this->gedoens = GeneralUtility::makeInstance(Gedoens::class);
    $activePagesExpiredInlast30days = $this->activePageRepository->findExpiredRecordsInTheLast30OR90Days(30);
    $itemsperpage = $this->settings['itemsPerPage'] ?? 50;

    $pageObjectArray = [];

    foreach ($activePagesExpiredInlast30days 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->gedoens->createCategoryFromSlug($activePage['slug']));
      $pageObj->setCreator($activePage['username']);
      $pageObj->setFullName($activePage['realName']);

      array_push($pageObjectArray, $pageObj);
    }
    $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 showLast90Action()
  {
      $this->gedoens = GeneralUtility::makeInstance(Gedoens::class);
    $activePagesExpiredInlast90days = $this->activePageRepository->findExpiredRecordsInTheLast30OR90Days(90);
    $itemsperpage = $this->settings['itemsPerPage'] ?? 50;

    $pageObjectArray = [];

    foreach ($activePagesExpiredInlast90days 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->gedoens->createCategoryFromSlug($activePage['slug']));
      $pageObj->setCreator($activePage['username']);
      $pageObj->setFullName($activePage['realName']);

      array_push($pageObjectArray, $pageObj);
    }
    $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();
    $actioName = '';

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

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