<?php

namespace Actigraph\ActipageBaseBundle\Controller;

use Actigraph\ActipageBaseBundle\Entity\Actus;
use Actigraph\ActipageBaseBundle\Entity\ModuleListe;
use Actigraph\ActipageBaseBundle\Entity\Objets;
use Actigraph\ActipageBaseBundle\Entity\Pages;
use Actigraph\ActipageBaseBundle\Services\ActipageService;
use Actigraph\ActipageBaseBundle\Services\CaptchaService;
use Actigraph\ActipageBaseBundle\Services\FilesService;
use Actigraph\ActipageBaseBundle\Services\NewsletterService;
use Doctrine\ORM\EntityManager;
use Actigraph\ActipageModulesReferentiel\FrontModules;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Router;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Translation\TranslatorInterface;
use \DateTime as DateTime;


class ActipageController extends ActipageBaseController
{

    //TODO site mobile = auto detection a faire, gestion cookies, modile (espace telechargement, enquéte )

    private $params;
    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * @Route("/maintenance", name="maintenance")
     */
    public function maintenanceAction(Request $request,ActipageService $actipageService, TranslatorInterface $translator){

        $this->handleLangueParam($actipageService);
        $maintenance = $actipageService->getCurrentMaintenance();
        if(!$maintenance)
            return $this->redirect($actipageService->generatePath("accueil"));

        $contenu = "TODO";

        $typeSiteFolder = "Default";
        if($actipageService->isMobileLangue())
            $typeSiteFolder = "Mobile";
        return $this->render('@ActigraphActipageBaseBundle/'.$typeSiteFolder.'/maintenance.html.twig', array(
            "contenu_titre"=>$maintenance["titre"],
            "contenu"=>$maintenance["texte"],
            "maintenanceMode" => true
        ));
    }

    /**
     * @Route("/search", name="recherche")
     */
    public function rechercheAction(Request $request,ActipageService $actipageService, TranslatorInterface $translator)
    {
        //TODO recherche a améliorer
        $this->handleLangueParam($actipageService);
        if($this->checkIfMaintenance($actipageService))
            return $this->redirect($actipageService->generatePath("maintenance"));

        $userSearchTxt = $request->query->get("rech","");
        $resultatsRecherche=array();
        $optionRecherche=array();
        $stringLengthError = false;
        if($userSearchTxt != ""){
            if(strlen($userSearchTxt) < 4){
                $this->redirect($request->getUri());
                $stringLengthError = true;
            } else {
                $titreIsSet = $request->query->get("titre",null);
                if($titreIsSet)
                    $optionRecherche[]="titre";

                $descIsSet = $request->query->get("desc",null);
                if($descIsSet)
                    $optionRecherche[]="desc";

                $motIsSet = $request->query->get("mot",null);
                if($motIsSet)
                    $optionRecherche[]="mot";

                $exactIsSet = $request->query->get("exact",null);
                if($exactIsSet)
                    $optionRecherche[]="exact";

                $contenuIsSet = $request->query->get("contenu",null);
                if($contenuIsSet)
                    $optionRecherche[]="contenu";

                $actuIsSet = $request->query->get("actu",null);
                if($actuIsSet)
                    $optionRecherche[]="actu";
                $resultatsRecherche = $actipageService->recherche($userSearchTxt,$optionRecherche);
            }
        }


        if (count($optionRecherche)==0)
            $optionRecherche = array("titre","desc","mot","contenu","exact","actu");

        $contenu = $this->renderView('@ActigraphActipageBaseBundle/Default/recherche.html.twig',array(
            "userSearchTxt"=>$userSearchTxt,
            "optionRecherche"=>$optionRecherche,
            "resultatsRecherche"=>$resultatsRecherche,
            "stringLengthError"=>$stringLengthError
        ));

        $typeSiteFolder = "Default";
        if ($actipageService->isMobileLangue())
            $typeSiteFolder = "Mobile";
        return $this->render('@ActigraphActipageBaseBundle/'.$typeSiteFolder.'/page.html.twig', array(
            "pagecustomstyleclass"=>"",
            "contenu_titre"=>$translator->trans("titre.recherche"),
            "contenu"=>$contenu,
        ));
    }

    /**
     * @Route("/legal", name="legal")
     */
    public function legalAction(ActipageService $actipageService,TranslatorInterface $translator)
    {
        $this->handleLangueParam($actipageService);
        if ($this->checkIfMaintenance($actipageService))
            return $this->redirect($actipageService->generatePath("maintenance"));

        $em = $this->get("doctrine")->getManager();
        $sql = 'SELECT accueil_mentions FROM accueil WHERE accueil_lang = :langueId';
        $query = $em->getConnection()->prepare($sql);
        $query->execute(array("langueId"=>$actipageService->getCurrentLangueId()));
        $legalContenu = $query->fetchAll();
        if (count($legalContenu) == 0)
            return false;

        $typeSiteFolder = "Default";
        if ($actipageService->isMobileLangue())
            $typeSiteFolder = "Mobile";

        return $this->render('@ActigraphActipageBaseBundle/'.$typeSiteFolder.'/page.html.twig', array(
            "isLegal"=>true,
            "pagecustomstyleclass"=>"",
            "contenu_titre"=>$translator->trans("titre.legal"),
            "contenu"=>$legalContenu[0]["accueil_mentions"],
        ));
    }

    /**
     * @Route("/sitemap", name="sitemap")
     */
    public function sitemapAction(ActipageService $actipageService, TranslatorInterface $translator)
    {
        $this->handleLangueParam($actipageService);
        if ($this->checkIfMaintenance($actipageService))
            return $this->redirect($actipageService->generatePath("maintenance"));

        $planDuSiteTxt = $translator->trans("label.footer.sitemap");

        $arboObj = $actipageService->generateArbo();
        $html  = "<div id='actiNav' class='col'>";
        $html .= "<ul><li><a role='heading' aria-level='1' href='".$actipageService->generatePath("accueil")."' >".$translator->trans("titre.accueil")."</a></li></ul>";
        $html .= $this->generateSitemap($arboObj);
        $html .= "<ul><li><a role='heading' aria-level='1' href='".$actipageService->generatePath("legal")."' >".$translator->trans("titre.legal")."</a></li></ul>";
        $html .= "<ul><li><a role='heading' aria-level='1' href='#' >".$planDuSiteTxt."</a></li></ul>";
        $html .= "</div>";

        return $this->render('@ActigraphActipageBaseBundle/Default/page.html.twig', array(
            "isSiteMap"=>true,
            "pagecustomstyleclass"=>"",
            "contenu_titre"=>$planDuSiteTxt,
            "contenu"=>$html,
        ));
    }

    /**
     * @Route("/", name="accueil")
     */
    public function accueilAction(Request $request,$lang,ActipageService $actipageService,EntityManagerInterface $entityManager)
    {
        $fileName = __DIR__.'/../../../../var/cache/accueil_'.strtolower($lang).'.cache';

        if (!is_dir(__DIR__.'/../../../../var/cache')) {
            mkdir(__DIR__.'/../../../../var/cache');
        }


        $ignoreCache = false;
        if (isset($this->params['cacheIgnoreHome']) && $this->params['cacheIgnoreHome'] == true) {
            $ignoreCache = true;
        }

        if (file_exists($fileName) && !$ignoreCache) {
            // Récupère la date de dernière modification du fichier
            $lastModifiedTime = filemtime($fileName);

            // Vérifie si le fichier a été modifié il y a plus de 20 secondes
            if (time() - $lastModifiedTime > 20) {
                // Met à jour le contenu du fichier
                //Gestion des permaliens ici maintenant car l'ancienne fonction dédié aux permaliens n'est plus accessible a cause des / ajouté automatiquement depuis SF4.1
                $repositoryObjets = $entityManager->getRepository('ActigraphActipageBaseBundle:Objets');
                $repositoryLang = $entityManager->getRepository('ActigraphActipageBaseBundle:Langues');
                $objet = $repositoryObjets->findOneByPermalien($lang);
                /** @var Objets $objet */
                if ($objet) { //Uniquement si la "langue" match à un permalien
                    $objetLangId = $objet->getObjLang();
                    $langConcerned = $repositoryLang->findOneByLangueId($objetLangId);

                    $shortcode = $langConcerned->getLangueShortCode();
                    $actipageService->setRequestedLang($shortcode);
                    $idEncoded = $actipageService->encodeId($objet->getObjId());

                    return $this->redirect($this->generateUrl("page", ["idEncoded" => $idEncoded, "slug" => $lang, "lang" => $shortcode]));
                }
                $this->handleLangueParam($actipageService);
                if ($this->checkIfMaintenance($actipageService)) {
                    return $this->redirect($actipageService->generatePath("maintenance"));
                }
                $em = $this->get("doctrine")->getManager();
                $sql = 'SELECT accueil_text FROM accueil WHERE accueil_lang = :langueId';
                $query = $em->getConnection()->prepare($sql);
                $query->execute(array("langueId"=>$actipageService->getCurrentLangueId()));
                $accueilContent = $query->fetchAll();

                if (count($accueilContent) == 0) {
                    throw new NotFoundHttpException("La page n'existe pas");
                }
                $contenu = $accueilContent[0]["accueil_text"];

                $twigFile = "Default";
                if ($actipageService->isMobileLangue()) {
                    $twigFile = "Mobile";
                }

                $return = $this->extendAndRender('@ActigraphActipageBaseBundle/'.$twigFile.'/accueil.html.twig', [
                    "content" => $this->getModuleOnPage($contenu, $request, 1),
                    "lang" => $lang,
                ],"accueilRender", [], $actipageService);
                file_put_contents($fileName, serialize($return));
            } else {
                $return = unserialize(file_get_contents($fileName));
            }
        } else {
            //Gestion des permaliens ici maintenant car l'ancienne fonction dédié aux permaliens n'est plus accessible a cause des / ajouté automatiquement depuis SF4.1
            $repositoryObjets = $entityManager->getRepository('ActigraphActipageBaseBundle:Objets');
            $repositoryLang = $entityManager->getRepository('ActigraphActipageBaseBundle:Langues');
            $objet = $repositoryObjets->findOneByPermalien($lang);
            /** @var Objets $objet */
            if ($objet) { //Uniquement si la "langue" match à un permalien
                $objetLangId = $objet->getObjLang();
                $langConcerned = $repositoryLang->findOneByLangueId($objetLangId);

                $shortcode = $langConcerned->getLangueShortCode();
                $actipageService->setRequestedLang($shortcode);
                $idEncoded = $actipageService->encodeId($objet->getObjId());

                return $this->redirect($this->generateUrl("page", ["idEncoded" => $idEncoded, "slug" => $lang, "lang" => $shortcode]));
            }
            $this->handleLangueParam($actipageService);
            if ($this->checkIfMaintenance($actipageService)) {
                return $this->redirect($actipageService->generatePath("maintenance"));
            }
            $em = $this->get("doctrine")->getManager();
            $sql = 'SELECT accueil_text FROM accueil WHERE accueil_lang = :langueId';
            $query = $em->getConnection()->prepare($sql);
            $query->execute(array("langueId"=>$actipageService->getCurrentLangueId()));
            $accueilContent = $query->fetchAll();

            if (count($accueilContent) == 0) {
                throw new NotFoundHttpException("La page n'existe pas");
            }
            $contenu = $accueilContent[0]["accueil_text"];

            $twigFile = "Default";
            if ($actipageService->isMobileLangue()) {
                $twigFile = "Mobile";
            }

            $return = $this->extendAndRender('@ActigraphActipageBaseBundle/'.$twigFile.'/accueil.html.twig', [
                "content" => $this->getModuleOnPage($contenu, $request, 1),
                "lang" => $lang,
            ],"accueilRender", [], $actipageService);
            file_put_contents($fileName, serialize($return));
        }

        return $return;
    }

    /**
     * @Route("/a/{idEncoded}",requirements={"idEncoded": "[A-Za-z0-9_-]+"}, name="detail_actu")
     */
    public function viewActuAction(Request $request,$idEncoded,$lang,ActipageService $actipageService, EntityManagerInterface $entityManager)
    {
        $this->handleLangueParam($actipageService);
        if ($this->checkIfMaintenance($actipageService))
            return $this->redirect($actipageService->generatePath('maintenance'));

        $actuId = $actipageService->decodeId($idEncoded);

        $idTypeInfoTrafic = [];
        $idTypeActualites = [];

        $moduleInfoTrafics = $actipageService->getModuleInfoFromModuleClass(FrontModules::MODULE_INFOTRAFIC);
        $moduleActulites = $actipageService->getModuleInfoFromModuleClass(FrontModules::MODULE_ACTUALITE);

        if (isset($moduleInfoTrafics['param_module'])) {
            $paramInfoTraf = json_decode($moduleInfoTrafics['param_module']);
            if(isset($paramInfoTraf->typeId)){
                $allType = explode(',', $paramInfoTraf->typeId);
                $idTypeInfoTrafic = $allType;
            }
        }

        if (isset($moduleActulites['param_module'])) {
            $paramActualites = json_decode($moduleActulites['param_module']);
            if(isset($paramActualites->typeId)){
                $allType = explode(',', $paramActualites->typeId);
                $idTypeActualites = $allType;
            }
        }

        /** @var Actus $actu */
        $actu = $entityManager->getRepository('ActigraphActipageBaseBundle:Actus')->findOneBy(['actuId' => $actuId]);
        if(is_null($actu)){
            $this->addFlash(
                'error',
                'Cette actualité n\'existe pas'
            );

            return $this->redirect($actipageService->generatePath('accueil'));
        }
        if (in_array($actu->getTypeActu()->getIdTypeActu(), $idTypeInfoTrafic)) {
            $objetWithActu =  $actipageService->findPageWithModuleClass(FrontModules::MODULE_INFOTRAFIC, false,false);
        } elseif(in_array($actu->getTypeActu()->getIdTypeActu(), $idTypeActualites)) {
            $objetWithActu = $actipageService->findPageWithModuleClass(FrontModules::MODULE_ACTUALITE, false, false);
        } else {
            $objetWithActu = $actipageService->findPageWithModuleClass(FrontModules::MODULE_ACTUALITE, false, false);
        }

        if (!$objetWithActu || empty($objetWithActu)) {
            if (in_array($actu->getTypeActu()->getIdTypeActu(), $idTypeInfoTrafic)) {
                $objetWithActu =  $actipageService->findPageWithModuleClass(FrontModules::MODULE_INFOTRAFIC, false,true);
            } elseif (in_array($actu->getTypeActu()->getIdTypeActu(), $idTypeActualites)) {
                $objetWithActu = $actipageService->findPageWithModuleClass(FrontModules::MODULE_ACTUALITE, false, true);
            } else {
                $objetWithActu = $actipageService->findPageWithModuleClass(FrontModules::MODULE_ACTUALITE, false, true);
            }
            $urlPage = $objetWithActu;
            $page = '';
        } else {
            if (is_array($objetWithActu)) {
                $idEncoded = $actipageService->encodeId($objetWithActu['obj_id']);
                $objet = $actipageService->getPage($idEncoded);
                if ($objet) { //Si j'ai objet (c'est qu'une page existe et est visitable
                    $urlPage = $actipageService->generateUrlForRawObjet($objetWithActu);
                    $page = $objet->getPage();
                } else{ //Pas de page ou alors page inactive
                    $urlPage = $objetWithActu;
                    $page = '';
                }
            } else {
                $urlPage = $objetWithActu;
                $page = '';
            }
        }

        $urlToShare = $request->getUri();

        if ($actu == null) {
            $this->addFlash(
                'error',
                'Cette actualité n\'existe pas'
            );
            if (!is_array($objetWithActu)) {
                return $this->redirect($objetWithActu);
            } else {
                return $this->redirect($actipageService->generateUrlForRawObjet($objetWithActu));
            }
        }

        if ($request->get('isVisibleToAdmin', 'false') !== 'true') {
            if ($actu->getActuDateDeb()->getTimestamp() > time() ||  time() > $actu->getActuDateFin()->getTimestamp()) {
                $this->addFlash(
                    'error',
                    'Cette actualité n\'existe pas'
                );
                if (!is_array($objetWithActu)) {
                    if ($objetWithActu == null) {
                        return $this->redirect('/');
                    }
                    return $this->redirect($objetWithActu);
                } else {
                    return $this->redirect($actipageService->generateUrlForRawObjet($objetWithActu));
                }
            }
        }

        if ($actu->getActuLien() != '') {
            return $this->redirect($actu->getActuLien());
        }
        $arrayData = [
            'unavailableAfter' => $actu->getActuDateFin(),
            'contenu_titre' => $actu->getActuTitre(),
            'contenu' => $actu->getActuTexte(),
            'actuTypeId' => $actu->getTypeActu()->getIdTypeActu(),
            'urlPage' => $urlPage,
            'isActu' => true,
            'urlToShare' => $urlToShare,
            'idTypeInfoTrafic' => $idTypeInfoTrafic,
            'idTypeActualites' => $idTypeActualites,
            'pagecustomstyleclass' => '',
        ];

        if ($page != '') {
            $arrayData["page"] = $page;
        }

        $typeSiteFolder = "Default";
        if ($actipageService->isMobileLangue())
            $typeSiteFolder = "Mobile";
        return $this->extendAndRender('@ActigraphActipageBaseBundle/'.$typeSiteFolder.'/page.html.twig',$arrayData,"viewActuRender", [$actu], $actipageService);
    }

    /**
     * @Route("/{idEncoded}-{slug}.html",requirements={"id": "[A-Za-z0-9_-]+","slug": "[a-zA-Z0-9\-_\.\/]+"}, name="page")
     */
    public function pageAction(Request $request,$idEncoded,$lang,$slug,ActipageService $actipageService, EntityManagerInterface $doctrine)
    {
        $isPreprod = $request->get('preprod');
        $isVisu = $request->get('visu');
        $this->handleLangueParam($actipageService);
        if ($this->checkIfMaintenance($actipageService))
            return $this->redirect($actipageService->generatePath("maintenance"));

        $this->handleLangueParam($actipageService);
        /** @var Objets $objet */
        if ($isVisu == 1)
            $objet = $actipageService->getPage($idEncoded, true);
        else
            $objet = $actipageService->getPage($idEncoded);


        if (!$objet)
            throw new NotFoundHttpException("La page n'existe pas");
        /** @var Pages $page */


        //Si je suis descendu dans une page enfant alors je redirige l'utilisateur vers l'url de la bonne page
        if($objet->getObjId() != $actipageService->decodeId($idEncoded))
            return $this->redirect($actipageService->generateUrlForObjet($objet));


        $urlPage = $request->getUri();
        $page = $objet->getPage();
        $request->attributes->set('current_object', $objet);
        $moduleComplementaire = "";
        if ($page->getPageLien() != "")
            return $this->redirect($page->getPageLien());

        if ($page->getPageExterne() > 0){
            //un module est lié a la page il faut le charger et recuperer les infos
            list($urlModule,$globalParams,$pageParams) = $actipageService->getModuleInfoFromPageId($page->getPageId());
            if ($urlModule != ""){
                $responseModule = $this->forward($urlModule,array(
                    "request"=>$request,
                    "globalParams"=>$globalParams,
                    "pageParams"=>$pageParams,
                    "em"=>$doctrine
                ));
                if ($responseModule->getStatusCode() != 404){ //si c'est pas un 404 car le module existe pas dans le symfony je l'affiche
                    $moduleComplementaire = $responseModule->getContent();
                }
                if ($responseModule->getStatusCode() === 302 || $responseModule->getStatusCode() === 301){
                    return $responseModule;
                }
            }
        }
        if ($isPreprod != 1) {
            $today = \DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
            if ($page->getPageTextPreprod() != '' && $page->getModifPreprod() == 1 && $page->getBrouillonDateDebut()->format('Y-m-d') != \DateTime::createFromFormat('d/m/Y', "00/00/00")->format('Y-m-d') && $today >= $page->getBrouillonDateDebut()) {
                $page->setPageText($page->getPageTextPreprod());
                $page->setModifPreprod(0);
                $page->setPageTextPreprod("");
                $page->setBrouillonDateDebut(\DateTime::createFromFormat('Y-m-d', "0000-00-00"));
                $em = $this->get("doctrine")->getManager();
                $em->persist($page);
                $em->flush();
            }
        }
        $contenu = ($isPreprod == 1) ? $page->getPageTextPreprod() : $page->getPageText();
        $contenu = $this->getModuleOnPage($contenu, $request, 0);
        $pagecustomstyleclass = "";
        if ($objet->getObjCustompageClass() != null)
            $pagecustomstyleclass = $objet->getObjCustompageClass()->getClass();
        $typeSiteFolder = "Default";
        if ($actipageService->isMobileLangue())
            $typeSiteFolder = "Mobile";
        return $this->extendAndRender('@ActigraphActipageBaseBundle/'.$typeSiteFolder.'/page.html.twig',array(
            'miniature' => $miniature ?? null,
            "page"=>$page,
            "titre"=>$page->getPageTitre(),
            "contenu_titre"=>$page->getPageTitre(),
            "pagecustomstyleclass"=>$pagecustomstyleclass,
            "contenu"=>$contenu,
            'moduleComplementaire' => $moduleComplementaire,
            "pageId"=>$idEncoded,
            "urlPage"=>$urlPage
        ),"pageRender",array($page,$idEncoded),$actipageService);
    }

    /**
     * @Route("/m/{idEncoded}",requirements={"idEncoded": "[A-Za-z0-9_-]+"}, name="module_detail")
     */
    public function viewModuleAction(Request $request,$idEncoded,$lang,ActipageService $actipageService, EntityManagerInterface $doctrine)
    {
        $moduleClass = $actipageService->decodeId($idEncoded);
        $em = $this->get("doctrine")->getManager();
        /** @var ModuleListe $moduleConcerned */
        $moduleConcerned = $em->getRepository('ActigraphActipageBaseBundle:ModuleListe')->findOneBy(array("classModuleFront"=>$moduleClass));

        $moduleParams = $moduleConcerned->getParamModule();
        $urlModule = $moduleConcerned->getFrontModuleClass();

        $responseModule = $this->forward($urlModule, [
            'request' => $request,
            'globalParams' => $moduleParams,
            'pageParams' => '',
            'em' => $doctrine,
        ]);

        $typeSiteFolder = "Default"; //TODO Gestion mobile ?
        return $this->render('@ActigraphActipageBaseBundle/'.$typeSiteFolder.'/page.html.twig', [
            "pagecustomstyleclass"=>"",
            "contenu_titre"=>$moduleConcerned->getNomModule(),
            "contenu"=>$responseModule->getContent(),
        ]);
    }

    /**
     * @Route("/rss/{typeActuId}",requirements={"typeActuId": "[0-9]+"}, name="flurss")
     */
    public function flurssAction(Request $request, $typeActuId, ActipageService $actipageService)
    {
        $em = $this->get("doctrine")->getManager();
        $repositoryActus = $em->getRepository('ActigraphActipageBaseBundle:Actus');
        $repositorySites = $em->getRepository('ActigraphActipageBaseBundle:Site');
        $site = $repositorySites->findOneBy(array());
        $domaine = $site->getDomaine();
        $actipageService->checkLangueInfo();
        $currentLang = $actipageService->getCurrentLangueShortCode();
        $currentLangID = $actipageService->getCurrentMereLangueId();
        $feedSelfUrl = $request->getSchemeAndHttpHost()."/".$currentLang."/rss/".$typeActuId;

        $allActuWithThisType = $actipageService->getActualitesByTypeId($typeActuId);

        $siteInforations = array(
            "name"=>$site->getNom(),
            "domain"=>$domaine,
            "lang"=>$currentLang,
            "selfurl"=>$feedSelfUrl
        );

        $allActusToDisplay = array();

        foreach ($allActuWithThisType as $actu) {
            $link = $actipageService->generatePath("detail_actu", array("idEncoded"=>$actipageService->encodeId($actu->getActuId())));
            $concernedLines = [];
            if ($actu->getLignes()) {
                foreach ($actu->getLignes() as $l) {
                    $concernedLines[] = [
                        'number' => $l->getLineCode(),
                        'name' => $l->getLineName(),
                    ];
                }
            }

            $allActusToDisplay[] = [
                "id" => $actu->getActuId(),
                "title" => $actu->getActuTitre(),
                "link" => $domaine.$link,
                "description" => $actu->getActuAccroche(),
                'concernedLines' => $concernedLines,
            ];
        }

        $response = new Response($this->renderView(
            '@ActigraphActipageBaseBundle/Default/fluxrss.xml.twig',
            array(
                'siteInformations'=>$siteInforations,
                'allactus' => $allActusToDisplay
            )
        ));

        $response->headers->set('Content-Type', 'text/xml');

        return $response;
    }

    /**
     * @Route("/updateprehome", name="update_prehome")
     */
    public function updatePrehomeSessionAction(Request $request,ActipageService $actipageService)
    {
        $response = new JsonResponse();

        $actipageService->setSessionPreHome(true);

        $response->setData(
            array(
                "status" => "success",
            )
        );
        return $response;
    }

    private function getInfoModuleFromId($id)
    {
        $em = $this->get("doctrine")->getManager();
        $sql = "SELECT * FROM module_liste where id_module =:idModule";
        $query = $em->getConnection()->prepare($sql);
        $query->execute(array("idModule"=>$id));
        $infosModule = $query->fetchAll();
        $urlModule = $globalParams = "";
        if(isset($infosModule[0])){
            $urlModule = $infosModule[0]["front_moduleClass"];
            $globalParams = $infosModule[0]["param_module"];
        }

        return array($urlModule, $globalParams);
    }

    private function getModuleOnPage($contenu, $request, $fromAccueil)
    {
        $tmp = explode("<a", $contenu);
        foreach ($tmp as $data){
            $tmp = explode('</a>', $data);
            foreach ($tmp as $htmlModule){
                if(strpos($htmlModule, 'data-module=')){
                    $htmlContent = "<a".$htmlModule."</a>";
                    $pageParams = $this->getParamsOfModule($htmlContent, 'data-params="', '"');
                    $dataModule = $this->getParamsOfModule($htmlContent, 'data-module="', '"');
                    $moduleId = $this->getParamsOfModule($htmlModule,'data-id="','"');
                    $dataColor = $this->getParamsOfModule($htmlModule,'data-color="','"');
                    list($urlModule,$globalParams) = $this->getInfoModuleFromId($moduleId);
                    if($urlModule != ""){
                        $moduleContent= $this->forward($urlModule,array(
                            "request"=>$request,
                            "globalParams"=>$globalParams,
                            "pageParams"=>$pageParams,
                            "em"=>$this->getDoctrine()
                        ));

                        $htmlContent = '/'.preg_quote($htmlContent, '/').'/';
                        $contenu = preg_replace($htmlContent, "<div data-module='".$dataModule."' class='".$dataColor."'>".$moduleContent->getContent()."</div>", $contenu);
                    } else {
                        $htmlContent = '/'.preg_quote($htmlContent, '/').'/';
                        $contenu = preg_replace($htmlContent, "<div data-module='".$dataModule."' class='".$dataColor."'>Le module n'existe pas</div>", $contenu);
                    }
                }
            }
        }

        return $contenu;
    }

    private function getParamsOfModule($content,$start,$end)
    {
        $r = explode($start, $content);

        if (isset($r[1])){
            $r = explode($end, $r[1]);
            return $r[0];
        }
        return '';
    }

    private function generateSitemap($listeArbo,$profondeur=0)
    {
        $html = "";
        foreach ($listeArbo as $arbo) {

            if ($profondeur == 0)
                $html .= "<ul>";
            $html .= '<li id="siteMap_x'.$arbo["id"].'">';
            $extraLink="";
            if ($arbo["type"] == "externe")
                $extraLink = "target='_blank'";
            $html .='<h'.($profondeur+1).' class="h5 mb-0 p-0 font-weight-normal"><a class="py-2" href="'.$arbo["url"].'" '.$extraLink.'>'.$arbo["titre"].'</a></h'.($profondeur+1).'>';
            if (count($arbo["enfants"]) > 0) {
                $html .= "<ul>";
                $html .= $this->generateSitemap($arbo["enfants"],$profondeur+1);
                $html .= "</ul>";
            }
            $html .= "</li>";
            if ($profondeur == 0)
                $html .= "</ul>";
        }
        return $html;
    }
}
