<?php

namespace Ayaline\Bundle\EzSitBundle\Controller;


use Ayaline\Bundle\EzSitBundle\Utils\SitUtils;
use eZ\Bundle\EzPublishCoreBundle\Controller;
use eZ\Publish\API\Repository\Values\Content\Query;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;

class EzAyaSitController extends Controller
{
    /**
     * @param $currentLocationId
     * @param $viewParameters
     * @param string $xslFile
     * @param null $idFicheEnCours
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function sitListAction($currentLocationId, $xslFile = "sit_liste", $idFicheEnCours = null)
    {
        $ezAyaSitLogger = $this->get('ayalineezsitbundle.ez_aya_sit.logger');
        $logger = $ezAyaSitLogger->getLogger();
        $translator = $this->get('translator');
        $viewParameters = $this->getGlobalHelper()->getViewParameters();
        // Initialisation des repositories
        $repository = $this->getRepository();
        $locationService = $repository->getLocationService();
        $contentService = $repository->getContentService();
        $contentTypeService = $repository->getContentTypeService();
        $helperContent = $this->get('ayaline_tools.tools.content');
        $sitListLocation = $locationService->loadLocation($currentLocationId);
        $sitListContent = $contentService->loadContent($sitListLocation->contentInfo->id);
        $sitListContentType = $contentTypeService->loadContentType($sitListLocation->contentInfo->contentTypeId);
        $sitListIdentifier = $sitListContentType->identifier;

        if ($sitListIdentifier !== "sit_liste") {
            $childContentList = $helperContent->contentList(
                $currentLocationId,
                array('sit_liste'),
                array(),
                1
            );
            if (!count($childContentList)) {
                return $this->render('AyalineEzSitBundle:errors:sit_liste_not_found.html.twig');
            }
            $sitListContent = $childContentList[0];
            $sitListLocation = $sitListContent->contentInfo->mainLocationId;
        }
        $request = $this->container->get('request');

        $sitUtils = new SitUtils($this, $this->container, $viewParameters, $logger, $request, $translator);
        $contenuBloc = $sitUtils->getSitListeHtml($currentLocationId, $sitListLocation, $sitListContent, $idFicheEnCours, $xslFile);

        return $this->render('AyalineEzSitBundle:parts:sit.html.twig', array(
            'contenuBloc' => $contenuBloc,
        ));
    }

    /**
     * @param $currentLocationId
     * @param $viewParameters
     * @param $request
     * @param string $xslFile
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function sitRechercheAction($currentLocationId, $xslFile = "sit_recherche")
    {
        $ezAyaSitLogger = $this->get('ayalineezsitbundle.ez_aya_sit.logger');
        $logger = $ezAyaSitLogger->getLogger();
        $translator = $this->get('translator');
        $viewParameters = $this->getGlobalHelper()->getViewParameters();
        // Initialisation des repositories
        $repository = $this->getRepository();
        $locationService = $repository->getLocationService();
        $contentService = $repository->getContentService();
        $contentTypeService = $repository->getContentTypeService();
        $helperContent = $this->get('ayaline_tools.tools.content');
        $sitListLocation = $locationService->loadLocation($currentLocationId);
        $sitListContent = $contentService->loadContent($sitListLocation->contentInfo->id);
        $sitListContentType = $contentTypeService->loadContentType($sitListLocation->contentInfo->contentTypeId);
        $sitListIdentifier = $sitListContentType->identifier;

        if ($sitListIdentifier !== "sit_liste") {
            $childContentList = $helperContent->contentList(
                $currentLocationId,
                array('sit_liste'),
                array(),
                1
            );
            if (!count($childContentList)) {
                return $this->render('AyalineEzSitBundle:errors:sit_liste_not_found.html.twig');
            }
            $sitListContent = $childContentList[0];
            $sitListLocation = $sitListContent->contentInfo->mainLocationId;
        }
        $request = Request::createFromGlobals();

        $sitUtils = new SitUtils($this, $this->container, $viewParameters, $logger, $request, $translator);

        $contenuBloc = $sitUtils->getSitRechercheHtml($currentLocationId, $sitListLocation, $sitListContent, $xslFile);

        return $this->render('AyalineEzSitBundle:parts:sit.html.twig', array(
            'contenuBloc' => $contenuBloc,
        ));
    }

    public function sitMiseEnAvantAction($currentLocationId, $modesAffichage = 1, $xslFile = "sit_mise_en_avant", $categories = false)
    {
        $ezAyaSitLogger = $this->get('ayalineezsitbundle.ez_aya_sit.logger');
        $helperContent = $this->get('ayaline_tools.tools.content');
        $logger = $ezAyaSitLogger->getLogger();
        $translator = $this->get('translator');
        $viewParameters = $this->getGlobalHelper()->getViewParameters();
        // Initialisation des repositories
        $repository = $this->getRepository();
        $locationService = $repository->getLocationService();
        $contentService = $repository->getContentService();
        $contentTypeService = $repository->getContentTypeService();

        $sitMeaLocation = $locationService->loadLocation($currentLocationId);
        $sitMeaContent = $contentService->loadContent($sitMeaLocation->contentInfo->id);
        $sitMeaContentType = $contentTypeService->loadContentType($sitMeaLocation->contentInfo->contentTypeId);
        $sitMeaIdentifier = $sitMeaContentType->identifier;


        if (!$categories) {
            $categories = array();
        }

        $categorie = array();

        $sitMiseEnAvantMatch = false;

        if ($sitMeaContent && $sitMeaIdentifier == 'sit_mise_en_avant') {
            $categorie = $sitMeaContent->getFieldValue('categorie')->selection;

            $tmp_catg = false;
            foreach ($categorie as $catg) {
                if (in_array($catg, $categories)) {
                    $tmp_catg = true;
                }
            }

            $modeAffichage = $sitMeaContent->getFieldValue('mode_affichage')->selection;
            $modeAffichage = $modeAffichage[0];

            if (($categories && (count($categories) == 0 || !(count($categorie) > 0)) || $tmp_catg) && (count($modesAffichage) == 0 || !$modeAffichage || in_array($modeAffichage, $modesAffichage))) {
                $sitMiseEnAvantMatch = true;
            }
        }


        $sitMiseEnAvantUrlAlias = "";
        $sitListeRelieeContentId = $sitMeaContent->getFieldValue('liste_reliee')->destinationContentId;
        $sitListeNodesIdentifiers = false;
        $sitListeNodes = false;

        if ($sitListeRelieeContentId !== null) {
            $sitListeRelieeContent = $contentService->loadContent($sitListeRelieeContentId);

            $sitListeContentIdentifier = $helperContent->getClassIdentifier($sitListeRelieeContent->contentInfo->mainLocationId);

            if ($sitListeContentIdentifier && $sitListeContentIdentifier == 'sit_liste') {
                $sitListeNodesIdentifiers = array($sitListeRelieeContent);
            }
        }


        if (!$sitListeNodesIdentifiers) {
            $listeCategSelection = $sitMeaContent->getFieldValue('categorie')->selection;

            $query = new Query();
            $query->criterion = new Criterion\LogicalAnd(
                array(
                    new Criterion\Field("categorie", Criterion\Operator::IN, $listeCategSelection),
                    new Criterion\ContentTypeIdentifier("sit_liste"),
                )
            );
            $searchResults = $this->getRepository()->getSearchService()->findContent($query);
            if (count($searchResults->searchHits)) {
                $sitListeNodes = $searchResults->searchHits;
            }
        }

        if (!$sitListeNodesIdentifiers && $sitListeNodes && count($sitListeNodes)) {
            $sitMiseEnAvantUrlAlias = $this->generateUrl(
                'ez_urlalias',
                array('locationId' => $sitListeNodes[0]->valueObject->contentInfo->mainLocationId)
            );
        } elseif ($sitListeNodesIdentifiers) {
            $sitMiseEnAvantUrlAlias = $this->generateUrl(
                'ez_urlalias',
                array('locationId' => $sitListeNodesIdentifiers[0]->contentInfo->mainLocationId)
            );
        }

        if(count($categories) == 0){
            $categories = $sitMeaContent->getFieldValue('categorie')->selection;
        }

        if(count($categories) == 1){
            $categorie = $categories[0];
        } else {
            $tempoCategories = "";
            foreach ($categories as $cle => $cat) {
                $tempoCategories .= $cat;
                if ($cle + 1 < count($categories)) {
                    $tempoCategories .= '|';
                }
            }
            $categorie = $tempoCategories;
        }

        $request = Request::createFromGlobals();

        $sitUtils = new SitUtils($this, $this->container, $viewParameters, $logger, $request, $translator);

        $contenuBloc = $sitUtils->getSitMiseEnAvantHtml($sitMeaLocation, $sitMeaContent, $categorie, $sitMiseEnAvantUrlAlias, $xslFile);

        return $this->render('AyalineEzSitBundle:parts:sit.html.twig', array(
            'contenuBloc' => $contenuBloc,
        ));
    }

    public function sitFicheDetailAction($ficheId, $cheminCategorie = '', $ficheTitle = '') {
        $ezAyaSitLogger = $this->get('ayalineezsitbundle.ez_aya_sit.logger');
        $logger = $ezAyaSitLogger->getLogger();
        $translator = $this->get('translator');
        $viewParameters = $this->getGlobalHelper()->getViewParameters();
        $request = $this->container->get('request');

        $sitUtils = new SitUtils($this, $this->container, $viewParameters, $logger, $request, $translator);
        $templateParameters['pagelayoutTemplate'] = $this->container->getParameter('SitFiche.Pagelayout.Template');
        $templateParameters['sitFicheTemplate'] = $this->container->getParameter('SitFiche.Detail.Template');

        $templateParameters = $sitUtils->getFicheDetail($ficheId, $cheminCategorie, $ficheTitle);
        return $this->render($templateParameters['sitFicheTemplate'], array(
            'contenuBloc' => $templateParameters['contenuBloc'],
            'intituleFiche' => $templateParameters['intituleFiche'],
            'parentLocationId' => $templateParameters['parentLocationId'],
            'pagelayoutTemplate' => $templateParameters['pagelayoutTemplate'],
            'descriptionFiche' => $templateParameters['descriptionFiche'],
            'idFiche' => $templateParameters['idFiche'],
        ));
    }

    public function lazyloadingAction()
    {
        $viewParameters = $this->getGlobalHelper()->getViewParameters();
        $sitLocationId = array_key_exists('locationId', $viewParameters) ? $viewParameters['locationId'] : '';
        return $this->sitListAction($sitLocationId, 'sit_liste_lazyloading');
    }
}