<?php

namespace Actigraph\ActipageBaseBundle\Twig;

use Actigraph\ActipageBaseBundle\Entity\Actus;
use Actigraph\ActipageBaseBundle\Entity\InfosComplementaires;
use Actigraph\ActipageBaseBundle\Entity\Lignes;
use Actigraph\ActipageBaseBundle\Entity\Objets;
use Actigraph\ActipageBaseBundle\Entity\Pages;
use Actigraph\ActipageBaseBundle\Entity\Miniature;
use Actigraph\ActipageModulesReferentiel\FrontModules;
use Actigraph\ActipageBaseBundle\Services\ActipageService;
use Actigraph\ActipageBaseBundle\Services\FilesService;
use Doctrine\ORM\EntityManagerInterface;
use Firebase\JWT\JWT;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\ItemInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Twig\TwigFilter;
use Twig\Environment;

class ActipageExtension extends AbstractExtension
{
    protected $actipageService;
    protected $translator;
    protected $doctrine;
    protected $twig_Environment;
    protected $baseHost;
    protected $router;
    protected $css_framework;
    protected $services;

    public function __construct(ActipageService $actipageService, TranslatorInterface $translator, EntityManagerInterface $doctrine, Environment $twig_Environment, RequestStack $requestStack, RouterInterface $router, FilesService $service)
    {
        $this->actipageService = $actipageService;
        $this->translator = $translator;
        $this->doctrine = $doctrine;
        $this->twig_Environment = $twig_Environment;
        $masterRequest = $requestStack->getMasterRequest();
        if($masterRequest != null)
            $this->baseHost = $requestStack->getMasterRequest()->getHost();
        $this->router = $router;
        $this->css_framework = $actipageService->getSiteConfigForModule("css_framework","BS3");
        $this->services=$service;
    }

    public function getFilters()
    {
        return array(
            new TwigFilter("stringToAlphaNumeric",array($this, 'stringToAlphaNumeric')),
        );
    }

    public function getFunctions()
    {
        return array(
            new TwigFunction("generateProtectedFileDownloadUrl",array($this, 'generateProtectedFileDownloadUrl')),
            new TwigFunction("generateAccueilPath",array($this, 'generateAccueilPath')),
            new TwigFunction("generateActuPath",array($this, 'generateActuPath')),
            new TwigFunction("generatePath",array($this, 'generatePath')),
            new TwigFunction("getCurrentPage",array($this, 'getCurrentPage')),
            new TwigFunction("dateDuJour",array($this, 'dateDuJour')),
            new TwigFunction("MenuSiteGauche",array($this, 'ArborescenceBuilderGauche'), array('is_safe' => array('html'))),
            new TwigFunction("MenuSiteHaut",array($this, 'ArborescenceBuilderHaut'), array('is_safe' => array('html'))),
            new TwigFunction("MenuSiteHautSousMenu",array($this, 'MenuSiteHautSousMenu'), array('is_safe' => array('html'))),
            new TwigFunction("MenuSiteHautSousMenuBS4",array($this, 'MenuSiteHautSousMenuBS4'), array('is_safe' => array('html'))),
            new TwigFunction("MenuSiteHautaccessible",array($this, 'ArborescenceBuilderHautaccessible'), array('is_safe' => array('html'))),
            new TwigFunction("MenuSiteLeftaccessible",array($this, 'ArborescenceBuilderLeftaccessible'), array('is_safe' => array('html'))),
            new TwigFunction("FilArianne",array($this, 'FilArianne'), array('is_safe' => array('html'))),
            new TwigFunction("LienAssociesPage",array($this, 'LienAssociesPage'), array('is_safe' => array('html'))),
            new TwigFunction("SearchBoxGauche",array($this, 'SearchBoxGauche'), array('is_safe' => array('html'))),
            new TwigFunction("SearchBoxHaut",array($this, 'SearchBoxHaut'), array('is_safe' => array('html'))),
            new TwigFunction("SearchBoxBS4",array($this, 'SearchBoxBS4'), array('is_safe' => array('html'))),
            new TwigFunction("DiaporamaBootstrapActus",array($this, 'DiaporamaBootstrapActus'), array('is_safe' => array('html'))),
            new TwigFunction("GetAlertActu",array($this, 'GetAlertActu')),
            new TwigFunction("GetPreHomeAlertActu",array($this, 'GetPreHomeAlertActu'), array('is_safe' => array('html'))),
            new TwigFunction("GetPreHomeAlertActuBS4",array($this, 'GetPreHomeAlertActuBS4'), array('is_safe' => array('html'))),
            new TwigFunction("DiaporamaAccueil",array($this, 'DiaporamaAccueil'), array('is_safe' => array('html'))),
            new TwigFunction("GetStyleActive",array($this, 'GetStyleActive'), array('is_safe' => array('html'))),
            new TwigFunction("GetChangementLangue",array($this, 'GetChangementLangue'), array('is_safe' => array('html'))),
            new TwigFunction("GetTarteAuCitron",array($this, 'GetTarteAuCitron'), array('is_safe' => array('html'))),
            new TwigFunction("AddToSocialNetworks",array($this, 'AddToSocialNetworks'), array('is_safe' => array('html'))),
            new TwigFunction("AddToSocialNetworksBS4",array($this, 'AddToSocialNetworksBS4'), array('is_safe' => array('html'))),
            new TwigFunction("GetNameClient",array($this, 'GetNameClient')),
            new TwigFunction("GetSEOPageInfos",array($this, 'GetSEOPageInfos')),
            new TwigFunction("GetSEOAccueilInfos",array($this, 'GetSEOAccueilInfos')),
            new TwigFunction("GetAccueilFileSite",array($this, 'GetAccueilFileSite')),
            new TwigFunction("GetRgpdForModule",array($this, 'GetRgpdForModule')),
            new TwigFunction("GetUrlSite",array($this, 'GetUrlSite')),
            new TwigFunction("GetCurrentLang",array($this, 'GetCurrentLang')),
            new TwigFunction("ModuleAccueil_GetNewsletter",array($this, 'ModuleAccueil_GetNewsletter')),
            new TwigFunction("ModuleAccueil_GetActu",array($this, 'ModuleAccueil_GetActu')),
            new TwigFunction("ModuleAccueil_LocationCar",array($this, 'ModuleAccueil_LocationCar')),
            new TwigFunction("ModuleAccueil_Twitter",array($this, 'ModuleAccueil_Twitter')),
            new TwigFunction("ModuleAccueil_Meteo",array($this, 'ModuleAccueil_Meteo')),
            new TwigFunction("ModuleAccueil_Timeo",array($this, 'ModuleAccueil_Timeo')),
            new TwigFunction("tunnelBundleHeader",array($this, 'tunnelBundleHeader')),
            new TwigFunction("getPageMiniature",array($this, 'getPageMiniature')),
            new TwigFunction("getInformationRapide",array($this, 'getInformationRapide')),


        );
    }
    public function getInformationRapide($page)
    {
        $info="";
        $infoObj = $this->doctrine->getRepository(InfosComplementaires::class)->findOneBy(["idPage" => $page->getPagePere()]);
        if ($infoObj != null) {
            if ($infoObj->getInformations() != null) {
                $info=$infoObj->getInformations();
            }
        }
        return $info;
    }

    public function getPageMiniature($page)
    {
        $url = '';
        $minia = $this->doctrine->getRepository(Miniature::class)->findOneBy(["idPage" => $page->getPagePere()]);
        if ($minia != null) {
            if ($minia->getImageMiniature() != null) {
                $filesService= $this->services;
                $url = $filesService->getTemporyUrlForPath("photos/__miniaturesPages/".$minia->getImageMiniature());
            }
        }
        return $url;
    }

    public function stringToAlphaNumeric($string)
    {
        return preg_replace('/[^A-Za-z0-9]/', '', $string);
    }

    public function tunnelBundleHeader()
    {
        $html = '';
//        $html .= '<meta name="test" content="TEST" />';
//        $html .= '<meta property="og:titles" content="mon test">';

        return $html;
    }

    public function GetAlertActu($overrideAlertesIds = null)
    {
        if($overrideAlertesIds == null){
            $idTypeBulletinAlertId = $this->actipageService->getIdTypeByNameTypeActu(ActipageService::ACTYTYPESEARCH_BULLETINALERTE);
            if(!$idTypeBulletinAlertId)
                return array();
        }else{
            $idTypeBulletinAlertId = $overrideAlertesIds;
        }
        /** @var Actus[] $alertActu */
        $alertActu = $this->actipageService->getActualitesByTypeId($idTypeBulletinAlertId);
        $alert = array();
        foreach ($alertActu as $actu ){
            $alert[] = array(
                "accroche"=>$actu->getActuAccroche(),
                "titre"=>$actu->getActuTitre(),
                "url"=>$this->generateActuPath($actu->getActuId()),
                "typeId"=>$actu->getIdTypeActu()
            );
        }

        return $alert;
    }


    public function GetPreHomeAlertActu($alertPlace)
    {
        $html ="";
        $params = $this->actipageService->getSiteParams();
        if(!isset($params["prehomePlace"]))
            return "";
        //$this->actipageService->setSessionPreHome(false);exit;

        if ( $params["prehomePlace"] == $alertPlace || $params["prehomePlace"] == "all" ){
            $typeActu = "";
            if($this->actipageService->getSessionPreHome() == false){

                $idTypeBulletinAlertId = $this->actipageService->getIdTypeByNameTypeActu(ActipageService::ACTYTYPESEARCH_ALERTE);
                if(!$idTypeBulletinAlertId)
                    return "";

                $alertActu = $this->actipageService->getActualitesByTypeId($idTypeBulletinAlertId);

                if(empty($alertActu)) {
                    $idPreHome = $this->actipageService->getIdTypeByNameTypeActu(ActipageService::ACTYTYPESEARCH_PREHOME);

                    if(strlen($idPreHome)>0)
                        $alertActu = $this->actipageService->getActualitesByTypeId($idPreHome);
                } else {
                    $typeActu = "alert";
                }

                if(!empty($alertActu)) {

                    $html = '<div class="modal fade" id="prehomeAlert" tabindex="-1" role="dialog" aria-labelledby="modalalerte">
                    <div class="modal-dialog '.$typeActu.'" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" id="closePrehomeAlert" class="close" data-dismiss="modal" aria-label="'.$this->translator->trans("label.closemodal").'"><span aria-hidden="true">&times;</span></button>
                                 <img src="/img/logo_modal.png" alt="'.$this->GetNameClient().'" class="logo">
                            </div><div class="modal-body">';


                    foreach ($alertActu as $actu) {
                        $html .= '<h1 id="modalalerte">' . $actu->getActuTitre() . '</h1>
                                    ' . $actu->getActuTexte() . '
                                    <hr>';
                    }

                    $html .= '</div>';
                    if ($params["preHomeDisableMode"] == "onBtnClose") {
                        $urlToDisableDef = $this->generatePath("update_prehome");
                        $html .= '<div class="modal-footer">
                                    <div class="row">
                                    <div class="col-md-6 text-left">
                                        <button type="button" id="closePrehomeDef" class="btn btn-link" data-url="' . $urlToDisableDef . '" data-dismiss="modal">'.$this->translator->trans("label.stopshowmodal").'</button>
                                    </div>
                                    <div class="col-md-6 text-right">
                                        <button type="button" class="btn btn-primary" data-dismiss="modal" aria-label=".$this->translator->trans("label.closemodal").">'.$this->translator->trans("label.accesausite").'</button>
                                    </div>
                                    </div>
                                  </div>';
                    }

                    $html .= '</div>
                    </div>
                </div>';

                }
                if($params["preHomeDisableMode"] == "afterOnview")
                    $this->actipageService->setSessionPreHome(true);
                else if($params["preHomeDisableMode"] == "none")
                    $this->actipageService->setSessionPreHome(false);
            }
        } else {
            if ($params["preHomeDisableMode"] == "afterOnview" && $params["prehomePlace"] =="home" && $alertPlace == "page") {
                $this->actipageService->setSessionPreHome(false);
            } //Si j'ai déjà vu la préhome en home, que je suis en auto close et en page interreur alors je marque comme non vu
        }

        return $html;
    }


    public function GetPreHomeAlertActuBS4($alertPlace)
    {
        $html ="";
        $params = $this->actipageService->getSiteParams();
        if(!isset($params["prehomePlace"]))
            return "";
        //$this->actipageService->setSessionPreHome(false);exit;

        if ( $params["prehomePlace"] == $alertPlace || $params["prehomePlace"] == "all" ) {
            $typeActu = "";
            if($this->actipageService->getSessionPreHome() == false){

                $idTypeBulletinAlertId = $this->actipageService->getIdTypeByNameTypeActu(ActipageService::ACTYTYPESEARCH_ALERTE);
                if(!$idTypeBulletinAlertId)
                    return "";

                $alertActu = $this->actipageService->getActualitesByTypeId($idTypeBulletinAlertId);

                if(empty($alertActu)) {
                    $idPreHome = $this->actipageService->getIdTypeByNameTypeActu(ActipageService::ACTYTYPESEARCH_PREHOME);

                    if(strlen($idPreHome)>0)
                        $alertActu = $this->actipageService->getActualitesByTypeId($idPreHome);
                } else {
                    $typeActu = "alert";
                }
                if (!empty($alertActu)) {

                    $html = '<div class="modal fade" id="prehomeAlert" tabindex="-1" role="dialog" aria-labelledby="modalalerte">
                    <div class="modal-dialog modal-lg modal-dialog-scrollable '.$typeActu.'" role="document">
                        <div class="modal-content">
                            <div class="modal-header bg-primary">

                                <img src="/img/logo_modal.png" alt="'.$this->GetNameClient().'" class="logo_modal">
                                <button type="button" class="close" data-dismiss="modal" aria-label="'.$this->translator->trans("label.closemodal").'">
                                  <span class="picto-close"></span>
                                </button>
                                
                            </div>
                            <div class="bg-warning p-1 bg-infotraf"></div>
                            <div class="modal-body">';


                    foreach ($alertActu as $actu) {
                        $html .= '<h1 id="modalalerte">' . $actu->getActuTitre() . '</h1>' . $actu->getActuTexte();
                    }

                    $html .= '</div>';
                    if ($params["preHomeDisableMode"] == "onBtnClose") {
                        $urlToDisableDef = $this->generatePath("update_prehome");
                        $html .= '<div class="modal-footer d-flex justify-content-between">
                                        <button type="button" id="closePrehomeDef" class="btn btn-outline-primary order-2 order-sm-1 py-1 py-sm-2 mb-0 mb-sm-1" data-url="' . $urlToDisableDef . '" data-dismiss="modal">'.$this->translator->trans("label.stopshowmodal").'</button>
                                        <button type="button" class="btn btn-primary order-1 order-sm-2 py-2 mb-2 mb-sm-1" data-dismiss="modal" aria-label="'.$this->translator->trans("label.closemodal").'">'.$this->translator->trans("label.accesausite").'</button>
                                  </div>';
                    }

                    $html .= '</div>
                    </div>
                </div>';

                }
                if($params["preHomeDisableMode"] == "afterOnview")
                    $this->actipageService->setSessionPreHome(true);
                else if($params["preHomeDisableMode"] == "none")
                    $this->actipageService->setSessionPreHome(false);
            }
        } else {
            if ($params["preHomeDisableMode"] == "afterOnview" && $params["prehomePlace"] =="home" && $alertPlace == "page") {
                $this->actipageService->setSessionPreHome(false);
            } //Si j'ai déjà vu la préhome en home, que je suis en auto close et en page interreur alors je marque comme non vu
        }

        return $html;
    }

    public function DiaporamaBootstrapActus($idTypeActu,$defaultImage=false, $defaultImageByType = false, $hideText = false, $isInfoTrafic = false, $pagination = false)
    {
        $listeActus = $this->actipageService->getActualitesByTypeId($idTypeActu);
        foreach ($listeActus as $key=>$actu){
            if($actu->getActuAlerte() == 0){
                unset($listeActus[$key]);
            }
        }
        $objets=array();
        if(empty($listeActus)){
            $objets[] = array(
                "image" => "/img/defaultimgdiapo.png",
                "imageAlt" => $this->translator->trans("label.defautimg"),
                "accroche" => "",
                "url" => "#",
                "urlExternal" => "",
            );
            $hideText = true;
        } else {
            foreach ($listeActus as $actu) {
                $imageUrl = "/photos/actus/" . $actu->getActuImage();
                /** @var Actus $actu */
                if (strlen(trim($actu->getActuImage())) == 0) {
                    if ($defaultImage == true && $defaultImageByType == false) {
                        $imageUrl = "/img/defaultimgdiapo.png";
                    } else if ($defaultImageByType == true) {
                        $imageUrl = "/img/defaultimgdiapo" . $actu->getIdTypeActu() . ".png";
                    }
                }

                if (strlen($imageUrl) > 0) {
                    $url = $this->generateActuPath($actu->getActuId());
                    if(strlen(trim($actu->getActuTexte())) == 0)
                        $url = "#";
                    if (strlen(trim($actu->getActuLien())) > 0) {
                        $url = $actu->getActuLien();
                    }
                    $urlExternal = false;
                    if ($actu->getActuLienCible() == 0)
                        $urlExternal = true;

                    $objets[] = array(
                        'idTypeActu' => $actu->getIdTypeActu(),
                        "lines" => $actu->getLignes()->toArray(),
                        "image" => $imageUrl,
                        "imageAlt" => $actu->getActuTitre(),
                        "accroche" => $actu->getActuAccroche(),
                        "url" => $url,
                        "urlExternal" => $urlExternal,
                    );
                }
            }
        }

        return $this->generateBootstrapDiaporama($objets, $hideText, 6000, "Évènements","fade", $isInfoTrafic, $pagination);
    }

    public function DiaporamaAccueil($idDiaporama)
    {
        $listeElements = $this->actipageService->getElementDiapoById($idDiaporama);
        $infosDiapo = $this->actipageService->getInfosDiapo($idDiaporama);

        $objets=array();

        foreach ($listeElements as $element){
            $imageUrl = $element->getFileName();

            if (strlen($imageUrl) == 0) {
                $imageUrl = "/diaporama/defaultimgdiapo.png";
            } else {
                $imageUrl = "/diaporama/".$infosDiapo->getImageFolder()."/".$imageUrl;
            }

            if (strlen($imageUrl) > 0) {
                if($element->getTarget() == "_blank")
                    $urlExternal = $element->getLink();
                else
                    $urlExternal = "";
                $objets[] = array(
                    "image" => "/photos".$imageUrl,
                    "imageAlt" => $element->getAlt(),
                    "accroche" => "",
                    "url" => $element->getLink(),
                    "urlExternal" => $urlExternal,
                );
            }
        }
        $diapo = "";

        if (!is_null($infosDiapo)) {
            $diapo = $this->generateBootstrapDiaporama($objets, true, $infosDiapo->getTempsAttente(), "Images",$infosDiapo->getAnimation());
        }

        return $diapo;
    }

    public function getCurrentPage()
    {
        return $this->actipageService->getCurrentPage();
    }

    protected function generateBootstrapDiaporama($objets, $hideText, $interval,$typdiapo,$modeAffichage="fade",$isInfoTrafic=false, $pagination = false)
    {
        if(count($objets)==0)
            return;

        if($modeAffichage == "fade"){
            $carrouselClass ="carousel carousel-fade";
        }else if($modeAffichage == "vertical"){
            $carrouselClass ="carousel carousel-vertical";
        }else{
            $carrouselClass ="carousel";
        }
        //Array avec image, url, urlExternal, imageAlt
        $idDiaporama = rand();
        $html = '<section id="myCarousel'.$idDiaporama.'" class="'.$carrouselClass.' slide" data-wrap="true" data-ride="carousel" data-interval="'.$interval.'" aria-roledescription="slide" aria-label="'.$typdiapo.'">';



        if(!$pagination){
            $html .=  '<ol class="carousel-indicators">';
            foreach ($objets as $index=>$objet){
                $class = "";
                if($index == 0)
                    $class ="active";
                $html .= '<li class="'.$class.'" data-target="#myCarousel'.$idDiaporama.'" data-slide-to="'.($index).'"  aria-hidden="true"><span class="sr-only">Écran '.($index+1).' sur '.count($objets).'</span></li>';
            }
            $html .= '</ol>';
        }else{
            $html .=  '<ol class="carousel-indicators carousel-infotrafic">';
            foreach ($objets as $index=>$objet){
                $class = "";
                if($index == 0)
                    $class ="active";
                $html .= '<li class="'.$class.'">'.($index+1).' sur '.count($objets).'</li>';
            }
            $html .= '</ol>';

        }

        $idTypeActu = $objet['idTypeActu'] ?? '';

        $html .= '<div class="carouselButtons"><button data-toggle="tooltip" data-placement="left" title="Lecture" type="button" class="playButton btn btn-link btn-xs none" aria-label="Lecture automatique du diaporama"><span class="glyphicon glyphicon-play"></span><span class="sr-only">Lire le diaporama</span></button><button data-toggle="tooltip" data-placement="left" title="Pause" type="button" class="pauseButton btn btn-link btn-xs" aria-label="Mettre le diaporama en pause"><span class="glyphicon glyphicon-pause"></span><span class="sr-only">Mettre le diaporama en pause</span></button></div><div class="carousel-inner" id="myCarousel-items'.$idDiaporama.'" aria-live="off">';
        foreach ($objets as $index=>$objet) {
            $class = "";
            if($index == 0)
                $class ="active";
            if($this->css_framework == "BS4")
                $html .=  '<div class="'.$class.' carousel-item" data-type-actu="'.$idTypeActu.'" role="group" aria-roledescription="slide" aria-label="'.($index+1).' sur '.count($objets).'">';
            else
                $html .=  '<div class="'.$class.' item" role="group" aria-roledescription="slide" aria-label="'.($index+1).' sur '.count($objets).'">';

            if (isset($objet["url"])) {
                if (($objet["url"]) == '') {
                    $html .= '<a href="/" title="'.$objet['imageAlt'].'">';
                } else {
                    $target = "_self";
                    $openOut = '';
                    if (isset($objet["urlExternal"]) && $objet["urlExternal"]) {
                        $target = '_blank';
                        $openOut = $this->translator->trans("label.in_new_window");
                    }
                    $html .= '<a href="'.$objet['url'].'" target="'.$target.'" title="'.$objet["imageAlt"].''.$openOut.'">';
                }
            }

            $alt = "Image diapositive";
            if(isset($objet["imageAlt"]))
                $alt = $objet["imageAlt"];

            if (!$isInfoTrafic) {
                $html .= '<img class="center-carousel" src="'.$objet["image"].'?rand='.time().'" alt="'.$alt.' '.$objet["accroche"].'">';
            }
            if($hideText == false){
                if ($isInfoTrafic) {
                    $html .= '<div class="carousel-caption">';
                    foreach ($objet['lines'] as $line) {
                        $html .= '<img class="indice" data-code="'.$line->getLinecode().'" src="/photos/__IndicesLignes/'.$line->getLinecode().'.png" alt="ligne '.$line->getLinecode().'">';
                    }

                    $html .= '<strong>'.$alt.'</strong><p>'.$objet["accroche"].'</p></div>';
                } else {
                    $html .= '<div class="carousel-caption"><h3>'.$alt.'</h3><p>'.$objet["accroche"].'</p></div>';
                }
            }

            if(isset($objet["url"])) {
                $html .= "</a>";
            }


            $html .= "</div>";
        }
        $html .= "</div>";

        $html .= '<button aria-controls="myCarousel-items'.$idDiaporama.'" aria-label="Contenu précédent" data-target="#myCarousel'.$idDiaporama.'" class="carousel-control left btn btn-link rounded-0" data-slide="prev" title="Voir le contenu précédent"><span class="picto-arrow-left" aria-hidden="true"></span><span class="sr-only">'.$this->translator->trans("label.previous").'</span></button> <button aria-controls="myCarousel-items'.$idDiaporama.'" aria-label="Contenu suivant"  data-target="#myCarousel'.$idDiaporama.'" class="carousel-control right btn btn-link rounded-0" data-slide="next" title="Voir le contenu suivant"><span class="picto-arrow-right" aria-hidden="true"></span><span class="sr-only">'.$this->translator->trans("label.next").'</span></button></section>';
        return $html;
    }

    public function generateAccueilPath()
    {
        return "/".$this->actipageService->getCurrentLangueShortCode()."/";
    }

    public function generatePath($path,$param=array())
    {
        return $this->actipageService->generatePath($path,$param);
    }

    public function generateProtectedFileDownloadUrl($remotePath, $remoteBasePath="", $nbrDayBeforeExpire=1)
    {
        $siteParams = $this->actipageService->getSiteParams();
        $token = array(
            "file_name"=> $remotePath,
            "exp"=>(time()+$nbrDayBeforeExpire*60*60*24)
        );
        if($remoteBasePath != "")
            $token["folder"]=$remoteBasePath;

        $token_file = JWT::encode($token,$siteParams["jwtSecret"],"HS256");
        $url_file = "http://".$this->baseHost.$this->router->generate('protectfile', ['jwtToken' => $token_file], UrlGeneratorInterface::ABSOLUTE_PATH);

        return $url_file;
    }

    public function generateActuPath($idActu)
    {
        return $this->generatePath("detail_actu",array("idEncoded"=>$this->actipageService->encodeId($idActu)));
    }

    public function dateDuJour()
    {
        //TODO gerer langues
        $jour = array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi");
        $mois = array("","Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre");
        return $jour[date("w")]." ".date("d")." ".$mois[date("n")]." ".date("Y");
    }

    public function SearchBoxGauche()
    {
        $pathRecherche = $this->generatePath("recherche");
        return '<form action="'.$pathRecherche.'" name="form_rech" id="form_recherche" method="get" class="form-search form-horizontal" style="background: transparent;"><div class="input-append"><label class="accessibilite" for="Recherche_Texte">'.$this->translator->trans("label.btn.rechercher").'</label><input class="search-query" id="Recherche_Texte" type="text" name="rech" size="12" placeholder="'.$this->translator->trans("label.your-search").'"><button type="submit" value="OK" name="recherche" class="btn "><i class="icon-search" data-original-title="" title=""></i><span class="accessibilite">OK</span></button></div></form>';
    }

    public function SearchBoxHaut()
    {
        $pathRecherche = $this->generatePath("recherche");
        return "
        <form class='navbar-form navbar-right' action='".$pathRecherche."' name='form_recherche' id='form_recherche' method='get' >
        <label class='sr-only control-label' for='Recherche_Texte'>".$this->translator->trans("label.recherche.btn.submit")."</label>
                <input type='hidden' value='1' name='recherche'/>
            <div class='input-group' id='recherche' role='search'>
              
                <input class='form-control' id='Recherche_Texte' type='text' name='rech' placeholder='".$this->translator->trans("label.recherche.btn.submit")."' />
                <span class='input-group-btn'>
            <button type='submit' class='btn btn-default'><span class='picto-loupe' aria-hidden='true'></span><span class='sr-only' >".$this->translator->trans("label.recherche.btn.submit")."</span></button>
                </span>
            </div>
          </form>";
    }

    public function SearchBoxBS4()
    {
        $pathRecherche = $this->generatePath("recherche");
        return "


        <form action='".$pathRecherche."' name='form_recherche' id='form_recherche' method='get' title='Rechercher'>
            <div class='input-group'>
                <label class='sr-only control-label' id='search-heading' for='Recherche_Texte'>".$this->translator->trans("label.recherche.btn.submit")."</label>
                <input type='hidden' value='1' name='recherche'/>
                <input id='Recherche_Texte' type='text' name='rech' placeholder='".$this->translator->trans("label.recherche.btn.submit")."' class='form-control form-control-sm' aria-label='".$this->translator->trans("label.recherche.btn.submit")."' title='".$this->translator->trans("label.recherche.btn.submit")."' aria-labelledby='search-heading'>
                <div class='input-group-append'>
                    <button class='btn btn-outline-light' type='submit' id='btnsearch'><span class='picto-loupe' aria-hidden='true'></span><span class='sr-only' >".$this->translator->trans("label.btn.rechercher")."</span></button>
                </div>
            </div>
          </form>";
    }

    public function LienAssociesPage(Objets $objet=null)
    {
        $html = "";
        if($objet == null)
            return $html;
        $sql = "SELECT * FROM pages_liens WHERE page_id=:page_id ORDER BY ordre";
        $query = $this->doctrine->getConnection()->prepare($sql);
        $query->execute(array("page_id"=>$objet->getObjId()));
        $pagesLiens = $query->fetchAll();
        if(count($pagesLiens)>0){
            $html ='<div class="list-group list-group-flush">';
            foreach ($pagesLiens as $item){
                $html .= '<a class="list-group-item list-group-item-action nocache" target="_blank" title="'.$item["nom"].' (nouvelle fenêtre)" href="'.$item["url"].'">'.$item["nom"].'</a>';
            }
            $html .="</div>";
        }

        return $html;
    }

    public function FilArianne($objet=null)
    {
        $html = "";

        $html .= "<li><a href='".$this->generateAccueilPath()."'>".$this->translator->trans("titre.accueil")."</a></li>"; //TODO utiliser translator
        if($objet == null)
            return $html;

        $parents = $this->actipageService->generateAllParentsFromObjet($objet);
        $parents = array_reverse($parents);
        $toEnd = count($parents);
        foreach ($parents as $key=>$parent){
            if($parent->getObjTitre() == "") //si c'est une page vide je ne l'affiche pas
                continue;
            /** @var Objets $parent */
            $html .="<li>";
            $html .= "<a href='".$this->actipageService->generateUrlForObjet($parent)."'>".$parent->getObjTitre()."</a>";
            if ($key != $toEnd)
                $html .="</li>";
        }

        return $html;
    }

    public function ArborescenceBuilderGauche()
    {
        $arboObj = $this->actipageService->generateArbo();
        $html = "<ul class='nav'>";
        $html .= $this->generateSubArbo($arboObj);
        $html .= "</ul>";
        return $html;
    }

    protected function generateSubArbo($listeArbo,$showOthersSubMenu=false,$showInSubMenu = false,$profondeurIndex=0)
    {
        $html = "";
        $nextProfondeurIndex = $profondeurIndex+1;
        foreach ($listeArbo as $arbo){
            if($showOthersSubMenu == false && $arbo["profondeur"] != 0 && in_array("active",$arbo["class"])==false && $showInSubMenu == false)
                continue; // Je ne prend pas en compte les sous menu s'ils sont pas actif

            $isActif = false;
            if(count($arbo["class"])>0 && in_array("active",$arbo["class"]))
                $isActif = true;
            $customTitle = "";
            if($isActif)
                $customTitle="title='".$arbo["titre"]." ".$this->translator->trans("label.footer.currentlyviewed.sr")."'";
            if($profondeurIndex>0)
                $html .= '<li class="'.implode(" ",$arbo["class"]).'" id="x'.$arbo["id"].'">';
            else
                $html .= '<li class="dropdown '.implode(" ",$arbo["class"]).'" id="x'.$arbo["id"].'">';
            $extraLink="";
            if($arbo["type"] == "externe"){
                $extraLink = "target='_blank'";
                $customTitle = "title='".$arbo["titre"]." ".$this->translator->trans("label.in_new_window")."'";
            }
            if($profondeurIndex>0)
                $html .='<a href="'.$arbo["url"].'" '.$extraLink.' '.$customTitle.' role="menuitem" >'.$arbo["titre"].'</a>';
            else
                $html .='<a class="dropdown-toggle" role="button" data-toggle="dropdown" data-target="#" href="'.$arbo["url"].'" '.$extraLink.'>'.$arbo["titre"].'</a>';

            if(count($arbo["enfants"])>0){
                if(in_array("active",$arbo["class"]))
                    $showInSubMenu = true;

                if($profondeurIndex>0)
                    $html .= '<ul class="" role="submenu">';
                else
                    $html .= '<ul class="dropdown-menu" role="menu" aria-labelledby="drop'.$arbo["id"].'">';

                $html .= $this->generateSubArbo($arbo["enfants"],$showOthersSubMenu,$showInSubMenu,$nextProfondeurIndex);
                $html .= "</ul>";
            }
            $html .= "</li>";
        }

        return $html;
    }


    public function ArborescenceBuilderHaut()
    {
        $arboObj = $this->actipageService->generateArbo();
        $html = "<ul class='nav navbar-nav'>";
        $html .= $this->generateSubArbo($arboObj,true);
        $html .= "</ul>";

        return $html;
    }

    protected function generateSubArboaccessible($listeArbo,$showOthersSubMenu=false,$showInSubMenu = false,$profondeurIndex=0,$spanAroundTitle=false)
    {
        $html = "";
        $nextProfondeurIndex = $profondeurIndex+1;
        foreach ($listeArbo as $arbo){
            if($showOthersSubMenu == false && $arbo["profondeur"] != 0 && in_array("active",$arbo["class"])==false && $showInSubMenu == false)
                continue; // Je ne prend pas en compte les sous menu s'ils sont pas actif
            $isActif = false;
            if(count($arbo["class"])>0 && in_array("active",$arbo["class"]))
                $isActif = true;
            $customTitle = "";
            if($isActif)
                $customTitle="title='".str_replace("'", '&#39;', $arbo["titre"])." ".$this->translator->trans("label.footer.currentlyviewed.sr")."'";
            if($profondeurIndex>0)
                $html .= '<li class="'.implode(" ",$arbo["class"]).'" id="x'.$arbo["id"].'">';
            else
                $html .= '<li class="nav-item '.implode(" ",$arbo["class"]).'" id="x'.$arbo["id"].'">';
            $extraLink="";
            if($arbo["type"] == "externe"){
                $extraLink = "target='_blank'";
                $customTitle = "title='".$arbo["titre"]." ".$this->translator->trans("label.in_new_window")."'";
            }
            if($profondeurIndex>0)
                $html .='<a href="'.$arbo["url"].'" '.$extraLink.' '.$customTitle.'>'.$arbo["titre"].'</a>';
            else{
                if($spanAroundTitle)
                    $arbo["titre"] = "<span>".$arbo["titre"]."</span>";
                $html .='<a class="head_menu" href="'.$arbo["url"].'" '.$extraLink.' '.$customTitle.'>'.$arbo["titre"].'</a>';
            }

            if(count($arbo["enfants"])>0){
                if(in_array("active",$arbo["class"]))
                    $showInSubMenu = true;

                if($profondeurIndex>0)
                    $html .= '<div class="sub-sub-nav"><ul class="sub-sub-nav-group" >';
                else
                    $html .= '<div class="sub-nav"><ul class="sub-nav-group">';

                $html .= $this->generateSubArboaccessible($arbo["enfants"],$showOthersSubMenu,$showInSubMenu,$nextProfondeurIndex);
                $html .= "</ul></div>";
            }
            $html .= "</li>";
        }

        return $html;
    }


    public function ArborescenceBuilderHautaccessible($withSearchBar=false)
    {
        $arboObj = $this->actipageService->generateArbo();
        $html = "<ul class='nav navbar-nav nav-menu '>";
        $html .= $this->generateSubArboaccessible($arboObj,true);
        if ($withSearchBar) {
            $html .= "<li>";
            $html .= $this->SearchBoxHaut($arboObj,true);
            $html .= "</li>";
        }
        $html .= "</ul>";

        return $html;
    }

    public function ArborescenceBuilderLeftaccessible($withSearchBar=false)
    {
        $arboObj = $this->actipageService->generateArbo();
        $html = "<ul class='nav navbar-nav nav-menu '>";
        $html .= $this->generateSubArboaccessible($arboObj,true,false,0,true);
        if($withSearchBar){
            $html .= "<li>";
            $html .= $this->SearchBoxHaut($arboObj,true);
            $html .= "</li>";
        }
        $html .= "</ul>";

        return $html;
    }

    public function MenuSiteHautSousMenu($withAffix=true)
    {
        $arboObj = $this->actipageService->generateArbo(true);
        $extraClass = "";
        if($withAffix)
            $extraClass = "affix";
        $html = "<nav class='bs-docs-sidebar $extraClass' aria-label='".$this->translator->trans("label.header.sousmenu.sr")."'><ul class='nav bs-docs-sidenav'>";
        $html .= $this->generateSideArbo($arboObj);
        $html .= "</ul></nav>";

        return $html;
    }

    public function MenuSiteHautSousMenuBS4($withAffix=true)
    {
        $arboObj = $this->actipageService->generateArbo(true);
        $extraClass = "";
        if($withAffix)
            $extraClass = "affix";
        $html = "<nav class='bs-docs-sidebar $extraClass' aria-label='".$this->translator->trans("label.header.sousmenu.sr")."'><ul class='nav bs-docs-sidenav'>";
        $html .= $this->generateSideArboBS4($arboObj);
        $html .= "</ul></nav>";

        return $html;
    }

    protected function generateSideArbo($listeArbo,$showInSubMenu=false)
    {
        $html = "";
        foreach ($listeArbo as $arbo){

            if($arbo["profondeur"] > 0){
                $isActif = false;
                if(count($arbo["class"])>0 && in_array("active",$arbo["class"]))
                    $isActif = true;
                $customTitle = "";
                if($isActif)
                    $customTitle="title='".str_replace("'", '&#39;', $arbo["titre"])." ".$this->translator->trans("label.footer.currentlyviewed.sr")."'";
                $html .= '<li class="s '.implode(" ",$arbo["class"]).'"  id="x'.$arbo["id"].'-sub">';
                $extraLink="";
                if($arbo["type"] == "externe"){
                    $extraLink = "target='_blank'";
                    $customTitle = "title='".$arbo["titre"]." ".$this->translator->trans("label.in_new_window")."'";
                }
                $html .='<a href="'.$arbo["url"].'" '.$extraLink.' '.$customTitle.'>'.$arbo["titre"].'</a>';
                if(count($arbo["enfants"])>0){
                    $html .= "<ul class='nav'>";
                    $html .= $this->generateSideArbo($arbo["enfants"],true);
                    $html .= "</ul>";
                }
                $html .= "</li>";
            }else if($arbo["profondeur"] == 0 && in_array("active",$arbo["class"])){
                $html .= $this->generateSideArbo($arbo["enfants"],$showInSubMenu);
            }
        }
        return $html;
    }

    protected function generateSideArboBS4($listeArbo,$showInSubMenu=false)
    {
        $html = "";
        foreach ($listeArbo as $arbo){

            if($arbo["profondeur"] > 0){
                $isActif = false;
                if(count($arbo["class"])>0 && in_array("active",$arbo["class"]))
                    $isActif = true;
                $customTitle = "";
                if($isActif)
                    $customTitle="title='".str_replace("'", '&#39;', $arbo["titre"])." ".$this->translator->trans("label.footer.currentlyviewed.sr")."'";

                $html .= '<li class="s '.implode(" ",$arbo["class"]).'" id="x'.$arbo["id"].'-sub">';
                $extraLink="";
                if($arbo["type"] == "externe"){
                    $extraLink = "target='_blank'";
                    $customTitle = "title='".$arbo["titre"]." ".$this->translator->trans("label.in_new_window")."'";
                }
                $html .='<div class="d-flex flex-row w-100 align-items-center justify-content-between"><a href="'.$arbo["url"].'" '.$extraLink.' '.$customTitle.' >'.$arbo["titre"].'</a></div>';
                if(count($arbo["enfants"])>0){
                    $html .= '<ul class="nav" id="ssx'.$arbo["id"].'-sub">';
                    $html .= $this->generateSideArbo($arbo["enfants"],true);
                    $html .= "</ul>";
                }
                $html .= "</li>";
            }else if($arbo["profondeur"] == 0 && in_array("active",$arbo["class"])){
                $html .= $this->generateSideArboBS4($arbo["enfants"],$showInSubMenu);
            }
        }
        return $html;
    }

    public function GetStyleActive()
    {
        $styleActive = $this->actipageService->getStyleSiteActive();
        $idStyle = $styleActive->getStyleId();

        return $idStyle;
    }

    public function GetChangementLangue()
    {
        return $this->actipageService->getLangueTraduction();
    }

    public function GetTarteAuCitron()
    {
        return $this->actipageService->getTarteAuCitron();
    }

    public function getName()
    {
        return 'actipage_extension';
    }

    public function AddToSocialNetworks($urlPage)
    {
        $html = '<div class="dropdown pull-right">
                  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    Partager
                    <span class="caret"></span>
                  </button>
                  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                        <li><a class="dropdown-item" target="_blank" href="http://twitter.com/home/?status='.$this->baseHost.$urlPage.'"><span class="picto-twitter" aria-hidden="true"></span> Twitter</a></li>
                        <li><a class="dropdown-item" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u='.$this->baseHost.$urlPage.'"><span class="picto-facebook" aria-hidden="true"></span> Facebook</a></li>
                        <li><a class="dropdown-item" target="_blank" href="https://www.linkedin.com/shareArticle?mini=true&url='.$this->baseHost.$urlPage.'"><span class="picto-linkedin" aria-hidden="true"></span> LinkedIn</a></li>
                        <li><a class="dropdown-item" target="_blank" href="mailto:?body='.$this->baseHost.$urlPage.'"><span class="picto-send" aria-hidden="true"></span> Mail</a></li>
                  </ul>
                </div>';

        return $html;
    }

    public function AddToSocialNetworksBS4($urlPage)
    {
        $html = '<div class="dropdown">
          <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownsocial" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Partager
          </button>
          <div class="dropdown-menu" aria-labelledby="dropdownsocial">
            <a class="dropdown-item" target="_blank" href="http://twitter.com/home/?status='.$this->baseHost.$urlPage.'"><span class="picto-twitter" aria-hidden="true"></span> Twitter</a>
            <a class="dropdown-item" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u='.$this->baseHost.$urlPage.'"><span class="picto-facebook" aria-hidden="true"></span> Facebook</a>
            <a class="dropdown-item" target="_blank" href="https://www.linkedin.com/shareArticle?mini=true&url='.$this->baseHost.$urlPage.'"><span class="picto-linkedin" aria-hidden="true"></span> LinkedIn</a>
            <a class="dropdown-item" target="_blank" href="mailto:?body='.$this->baseHost.$urlPage.'"><span class="picto-send" aria-hidden="true"></span> Mail</a>
          </div>
        </div>';

        return $html;
    }

    public function GetNameClient()
    {
        $clientInfos =  $this->actipageService->getClientInfos();
        $clientName = $clientInfos->getNom();

        return $clientName;
    }

    public function GetUrlSite()
    {
        $clientInfos =  $this->actipageService->getClientInfos();
        $domaine = $clientInfos->getDomaine();

        return $domaine;
    }

    public function GetCurrentLang()
    {
        return $this->actipageService->getCurrentLangueShortCodeRef();
    }

    public function GetSEOPageInfos(Pages $pages)
    {
        $seo = array(
            "desc"=>$pages->getPageDesc(),
            "keywork"=>$pages->getPageMot(),
            "title"=>$pages->getPageTitre()
        );
        return $seo;
    }

    public function GetSEOAccueilInfos($type = "accueil")
    {
        if($type == "legal"){
            $seo = array(
                "desc"=>$this->translator->trans("titre.legal"),
                "keywork"=>$this->translator->trans("titre.legal"),
                "title"=>$this->translator->trans("titre.legal"),
            );
        } elseif ($type == "siteMap"){
            $seo = array(
                "desc"=>$this->translator->trans("label.footer.sitemap"),
                "keywork"=>$this->translator->trans("label.footer.sitemap"),
                "title"=>$this->translator->trans("label.footer.sitemap"),
            );
        } else {
            $accueilInfo = $this->actipageService->getPageAccueilInfos();
            if ($accueilInfo != null) {
                $seo = [
                    "desc" => $accueilInfo->getAccueilDesc(),
                    "keywork" => $accueilInfo->getAccueilMot(),
                    "title" => $accueilInfo->getAccueilTitre(),
                ];
            } else {
                $seo = [
                    "desc" => '',
                    "keywork" => '',
                    "title" => '',
                ];
            }
        }

        return $seo;
    }

    public function GetAccueilFileSite($lang, $mode)
    {
        $fileToExtend = "templates/site/accueil_".$lang.".html.twig";

        if(file_exists(dirname(__FILE__)."/../../../../".$fileToExtend))
            $file =  "@AppBundle/".$mode."/accueil_".$lang.".html.twig";
        else
            $file = "@AppBundle/".$mode."/accueil.html.twig";


        return $file;
    }


    public function GetRgpdForModule($moduleClass)
    {
        $html = "";
        $moduleRgpd = $this->actipageService->getModuleRgpdInfo($moduleClass);

        //return $moduleRgpd;
        if($moduleRgpd["asRgpd"] == 0)
            return "";
        elseif ($moduleRgpd["showRgpd"] == 0)
            return  "";

        if(!is_null($moduleRgpd["labelContent"]) && $moduleRgpd["labelContent"] != "") {

            $html .= '
            <div class="custom-control custom-checkbox mb-3">
              <input name="rgpdAccepted" type="checkbox" class="custom-control-input" id="rgpdAccepted-'.$moduleClass.'" value="rgpdAccepted" required>
              <label class="custom-control-label" for="rgpdAccepted-'.$moduleClass.'">' . $moduleRgpd["labelContent"] . ' <abbr tabindex="0" title="obligatoire">*</abbr></label>
            </div>';

            $html .= '<script nonce="{{ ContentSecurityPolicyNonceService.nonce }}" type="text/javascript">
                        
                        function isRgpdAccepted(formId){
                            if(document.getElementById(formId).rgpdAccepted.checked){
                                return true;
                            }
             
                            return false;
                        }
                        
                      </script>';
        }

        if(!is_null($moduleRgpd["rgpdContent"]) && $moduleRgpd["rgpdContent"] != "") {

            $html .= '<div class="well">'.$moduleRgpd["rgpdContent"].'</div>';
        }

        return $html;
    }

    public function ModuleAccueil_Timeo($globalParams)
    {
        if ($globalParams == "")
            $globalParams = array();
        else {
            $globalParams = json_decode($globalParams, true);
            if (!$globalParams)
                $globalParams = array();
        }
        $globalParams = array_merge(array("reseau" => 0,"token"=>"","itineraireTopRightLink" => "false"), $globalParams);
        $lignes = [];
        if($globalParams["reseau"]>0){
            $lignes = $this->actipageService->getProchainsPassagesTimeoLignes($globalParams["reseau"],$globalParams["token"]);
        }
        if($globalParams["itineraireTopRightLink"] == "false")
            $globalParams['itineraireTopRightLink']=false;

        $urlPageModule = $this->actipageService->findPageWithModuleClass(FrontModules::MODULE_TIMEO, false,true);
        if($urlPageModule == "")
            return;
        $globalParams["urlForm"] = $urlPageModule;

        return $this->twig_Environment->render('@ActigraphActipageBaseBundle/ModuleAccueil/tpl/formulairetimeo_accueil.html.twig', array(
            "params" => $globalParams,
            "lignes"=>$lignes
        ));
    }

    public function ModuleAccueil_GetNewsletter($globalParams)
    {
        $params = json_decode($globalParams, true);
        $pageId = null;

        if (isset($params["idPageNewsletter"]))
            $pageId = $params["idPageNewsletter"];

        if ($pageId == null || $pageId == "") {
            $pageWithModule = $this->actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER, false,false);
            if ($pageWithModule == false) {
                $pageWithModule = $this->actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER_AVANCEE, false,false);
            }
            if($pageWithModule == false)
                return "";
            $pageId = $pageWithModule["page_id"];
        }

        $repositoryPages = $this->doctrine->getRepository('ActigraphActipageBaseBundle:Pages');
        $pageConcerned = $repositoryPages->findOneBy(array("pageId" => $pageId));
        if(!empty($pageConcerned)){
            $objetConcerned = $pageConcerned->getObjet();
            $urlObj = $this->actipageService->generateUrlForObjet($objetConcerned);
        }

        return $this->twig_Environment->render("@ActigraphActipageBaseBundle/ModuleAccueil/tpl/newsletter_accueil_tpl.html.twig", ["urlForm"=>$urlObj]);
    }

    public function ModuleAccueil_GetActu($params)
    {
        $html = "";
        $params = json_decode($params, true);
        $source = $params["source"];
        $sourceOption = $params["sourceOption"];
        $idPageCible = $params["idPageCible"];
        $affichage = $params["affichage"];
        if($idPageCible == "")
            return new Response('');

        $asActuLines = $this->actipageService->isClientAsOption("asActuLines");
        $repositoryLines = $this->doctrine->getRepository('ActigraphActipageBaseBundle:Lignes');

        $repositoryPages = $this->doctrine->getRepository('ActigraphActipageBaseBundle:Pages');
        $repositoryObjets = $this->doctrine->getRepository('ActigraphActipageBaseBundle:Objets');
        $pageConcerned = $repositoryObjets->findOneBy(array("objId" => $idPageCible));
        if(empty($pageConcerned))
            return new Response("");

        $objetConcerned = $pageConcerned;
        $urlObj = $this->actipageService->generateUrlForObjet($objetConcerned);
        if ($source == "actus") {
            $perturbations = array();
            $actus = $this->actipageService->getActualitesByTypeId($sourceOption);

            $repositoryTypeActu = $this->doctrine->getRepository('ActigraphActipageBaseBundle:TypeActu');
            $actuTypeConcerned = $repositoryTypeActu->findOneBy(array("idTypeActu" => $sourceOption));
            $typeActuName = $actuTypeConcerned->getNomTypeActu();

            $allLines = array();
            /** @var Actus $actu */
            foreach ($actus as $actu) {
                $lignes = array();
                if ($asActuLines && $typeActuName == "Infos trafic") {
                    /** @var Lignes $lineConcerned */
                    foreach ($actu->getLignes() as $lineConcerned) {
//                        $lineConcerned = $repositoryLines->findOneBy(array("lineexternalcode" => $ligne->getLineexternalcode()));
//                        /** @var Lignes $lineConcerned */
//                        $lineConcerned = $ligne->getLigne();
                        $lineCode = preg_replace('/[^A-Za-z0-9\-]/', '', $lineConcerned->getLinecode());
                        $lineCode = strtolower($lineCode);
                        $line = array(
                            "id" => $lineConcerned->getLineexternalcode(),
                            "indiceId" => "",
                            "code" => $lineCode,
                            "nom" => $lineConcerned->getLinename(),
                            "urlIndice" => $urlObj . "?indice=" . $lineCode,
                            "ordre"=>$lineConcerned->getOrdre()
                        );
                        $lignes[] = $line;
                        array_push($allLines, $line);
                    }

                    $allLines = array_unique($allLines, SORT_REGULAR);
                    usort($allLines, function ($item1, $item2) {
                        return $item1['ordre'] <=> $item2['ordre'];
                    });
                }

                $debut = $actu->getActuDateDebEve();
                $fin = $actu->getActuDateFinEve();
                if($debut->format("d/m/y") ==  $fin->format("d/m/y") && $debut->format("H:i")  == "00:00" && $fin->format("H:i") == "23:59"){
                    $agenda =  "<div class='date-agenda'>(Le ".$debut->format("d/m/y").")</div>";
                } else if($debut->format("H:i") == "00:00" && $fin->format("H:i") == "23:59"){
                    $agenda =  "<div class='date-agenda'>(Du ".$debut->format("d/m/y")." au ".$fin->format("d/m/y").")</div>";
                } else if($debut->format("d/m/y") == $fin->format("d/m/y")){
                    $agenda =  "<div class='date-agenda'>(Le ".$debut->format("d/m/y")." de <span class='label label-default'>".$debut->format("H")."H". $debut->format("i") ."</span> à <span class='label label-default'>".$fin->format("H")."H". $fin->format("i") .")</span></div>";
                } else {
                    $agenda =  "<div class='date-agenda'>(Du ".$debut->format("d/m/y") ."<span class='label label-default'>".$debut->format("H:i")."</span> au ".$fin->format("d/m/y") ."<span class='label label-default'>".$fin->format("H:i")."</span>)</div>";
                }

                $perturbations[] = array(
                    "id" => $actu->getActuId(),
                    "titre" => $actu->getActuTitre(),
                    "message" => $actu->getActuAccroche(),
                    "contenu" => $actu->getActuTexte(),
                    "actuLink" => $this->actipageService->generatePath("detail_actu", array("idEncoded" => $this->actipageService->encodeId($actu->getActuId()))),
                    "lignes" => $lignes,
                    "dateDebut" => $actu->getActuDateDeb(),
                    "dateFin" => $actu->getActuDateFin(),
                    "agenda" => $agenda,
                    "gravite" => $actu->getGraviteActu(),
                    "Image" => $actu->getActuImage()
                );
            }
        }

        if ($affichage["type"] == "liste") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/ModuleAccueil/tpl/actu_accueil_liste_tpl.html.twig";
        } else if ($affichage["type"] == "diapo") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/ModuleAccueil/tpl/actu_accueil_diapo_tpl.html.twig";
        } else if ($affichage["type"] == "indices") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/ModuleAccueil/tpl/actu_accueil_indices_tpl.html.twig";
        } else if ($affichage["type"] == "indices_scroll") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/ModuleAccueil/tpl/actu_accueil_indices_scroll_tpl.html.twig";
        } else if ($affichage["type"] == "scroll") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/ModuleAccueil/tpl/actu_accueil_scroll_tpl.html.twig";
        }

        return $this->twig_Environment->render($viewToRedirect, [
            "source"=>$sourceOption,
            "actus" => $perturbations,
            "affichage" => $affichage,
            "typeActu" => $typeActuName,
            "lines" => $allLines,
            "urlObjet" => $urlObj
        ]);
    }

    public function ModuleAccueil_LocationCar($params)
    {
        $params = json_decode($params, true);
        $pageId = null;
        $urlForm = "";
        if (isset($params["idPageLocationCar"])){
            $pageId = $params["idPageLocationCar"];

            $repositoryPages = $this->doctrine->getRepository('ActigraphActipageBaseBundle:Pages');
            $pageConcerned = $repositoryPages->findOneBy(array("pageId" => $pageId));
            if($pageConcerned){ //Si la page déclaré existe je genere l'url dessus
                $objetConcerned = $pageConcerned->getObjet();
                $urlForm = $this->actipageService->generateUrlForObjet($objetConcerned);
            }
        }
        if(!$urlForm){
            $urlForm = $this->actipageService->findPageWithModuleClass(FrontModules::MODULE_FORM_DEVIS, false);
        }
        return $this->twig_Environment->render("@ActigraphActipageBaseBundle/ModuleAccueil/tpl/location-car_tpl.html.twig", ["urlForm"=>$urlForm]);
    }

    public function ModuleAccueil_Twitter($params)
    {
        return "<div><a class=\"twitter-timeline\" href=\"https://twitter.com/".$params->twitterAccount."\"  data-chrome=\"nofooter\">Tweets de ".$params->twitterAccount."</a>
                     <script type=\"text/javascript\">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+\"://platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script></div>";
    }

    public function ModuleAccueil_Meteo($globalParams)
    {
        $cache = new FilesystemAdapter();

        $paramsClient = $this->actipageService->getSiteParams();
        $params = json_decode($globalParams);
        $key = $paramsClient["openWeatherMap"]["key"];
        $city = $params->city;
        $cityName = $params->cityName;
        $meteoTodayCache = $cache->getItem('meteo.today')->expiresAfter(60);
        $meteoTommorowCache = $cache->getItem('meteo.tommorow')->expiresAfter(60);

        if ($meteoTodayCache->isHit() && $meteoTommorowCache->isHit()) {
            $meteoToday = $meteoTodayCache->get();
            $meteoTommorow = $meteoTommorowCache->get();
        } else {//TODO passer par un service plutot ?
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'http://api.openweathermap.org/data/2.5/forecast?id=' . $city . '&units=metric&lang=fr&APPID=' . $key);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $resp = curl_exec($ch);
            curl_close($ch);

            $meteo = json_decode($resp);

            if($meteo->cod == 401)
                return "";
            $prevision = array();
            foreach ($meteo->list as $data) {
                $prevision[] = $data;
            }

            $meteoToday = $this->getMeteo($prevision[0], $cityName);

            $meteoTommorow = array();
            $tommorow = new \DateTime();
            $tommorow->add(new \DateInterval("P1D"));
            $tommorow->setTime(11, 59, 00); //le lendemain à 11h59
            foreach ($prevision as $data) {
                if (new \DateTime($data->dt_txt) > $tommorow && $meteoTommorow == []) //si je dépasse 11h59 le lendemain je retourne la prévision en cours. Retourne donc la prévision du demain 12h
                    $meteoTommorow = $this->getMeteo($data, $cityName);
            }
            $meteoTodayCache->set($meteoToday);
            $meteoTommorowCache->set($meteoTommorow);

            $cache->save($meteoTodayCache);
            $cache->save($meteoTommorowCache);
        }

        return $this->twig_Environment->render("@ActigraphActipageBaseBundle/ModuleAccueil/tpl/meteo_tpl.html.twig", [
            "meteo" => $meteoToday,
            "tommorow" => $meteoTommorow
        ]);
    }

    protected function getMeteo($data, $cityName)
    {
        $meteo = array(
            "temp" => $data->main->temp,
            "cityName"=>$cityName,
            "codeMeteo" => $data->weather[0]->id,
            "codeIcone" => $data->weather[0]->icon,
            "description" => $data->weather[0]->description,
            "previsionDate" => new \DateTime($data->dt_txt),
        );

        return $meteo;
    }
}
