<?php

namespace Meramo\Pagemanager\Controller;

use Meramo\Pagemanager\Domain\Model\ActivePage;
use TYPO3\CMS\Backend\View\BackendTemplateView;
use TYPO3\CMS\Core\Http\HtmlResponse;
use TYPO3\CMS\Core\Http\ServerRequestFactory;
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 PageRenderer $pageRenderer;
  protected ActivePageRepository $activePageRepository;

  public function __construct(
    ActivePageRepository $activePageRepository
  ) {
    $this->activePageRepository = $activePageRepository;
  }
    protected function resolveView()
    {
        $view = parent::resolveView();

        $view->assignMultiple([
            'extensionName' => $this->request->getControllerExtensionName(),
            'controllerName' => $this->request->getControllerName(),
            'actionName' => $this->request->getControllerActionName()
        ]);
        return $view;
    }

    protected function generateMenu()
    {
        $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'
            ],
        ];
        $menu = $this->view->getModuleTemplate()->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->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->addMenu($menu);
    }

    protected function getHref($controller, $action, $parameters = [])
    {
        $uriBuilder = $this->objectManager->get(UriBuilder::class);
        $uriBuilder->setRequest($this->request);
        return $uriBuilder->reset()->uriFor($action, $parameters, $controller);
    }

//    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'
//          ],
//      ];
//
//      if (class_exists(ModuleTemplateFactory::class)) {
//          $moduleTemplateFactory = GeneralUtility::makeInstance(ModuleTemplateFactory::class);
//          $request = $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
//          $this->moduleTemplate = $moduleTemplateFactory->create($request);
//      } elseif (class_exists(ModuleTemplate::class)) {
//          $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
//      } else {
//          throw new \RuntimeException('Unable to instantiate module template class.', 1615368623);
//      }
//
//      $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;
//              }
//          }
//          $bla = $this->getHref($menuItemConfig['controller'], $menuItemConfig['action']);
//
//          $menuItem = $menu->makeMenuItem()
//              ->setTitle($menuItemConfig['label'])
//              ->setHref("/typo3/module/tools/PagemanagerPgmgt?token=b36b5554410fad12243b2127c156584d72a80b69&tx_pagemanager_tools_pagemanagerpgmgt%5Baction%5D=index&tx_pagemanager_tools_pagemanagerpgmgt%5Bcontroller%5D=Backend")
////              ->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->view->setContent($this->view->render());
      return new HtmlResponse($this->view->renderContent());
//    $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 new HtmlResponse($this->moduleTemplate->renderContent());
//    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
      ]
    );
  }
}
