<?php
    namespace Cadoles\CoreBundle\EventListener;

    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Symfony\Component\EventDispatcher\EventDispatcher;
    use Symfony\Component\EventDispatcher\Event;
    use Symfony\Component\HttpFoundation\Session\Session;
    use Doctrine\ORM\EntityManager;

    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
	use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

    class sessionListener {
        protected $container;
        protected $em;
        protected $token_storage;
        protected $session;

        public function __construct($container, EntityManager $em, TokenStorageInterface $token_storage,Session $session)
        {
            $this->container = $container;
            $this->em = $em;
            $this->token_storage = $token_storage;
            $this->session = $session;
        }

        public function haveRole($curentuser,$roles,$tohave,$route) {
            $haverole=false;
            if($roles=="") {
                if(empty($tohave)) $haverole=true;
            }
            else {
                foreach($roles as $role) {
                    if(in_array($role,$tohave))
                        $haverole=true;
                }
            }
            
            if($route!=null) {
                if($haverole&&in_array("ROLE_MODO",$roles)) {
                    $permmodo=$this->em->getRepository("CadolesCoreBundle:PermModo")->findOneBy(["route"=>$route,"visible"=>true,"permmodoprofil"=>$curentuser->getPermmodoprofil()]);
                    if(!$permmodo) $haverole=false;
                } 
            }

            return $haverole;
        }

        public function onDomainParse(Event $event) {
            $session = $this->session;

            $configs = $this->em->getRepository("CadolesCoreBundle:Config")->findAll();
            foreach($configs as $config) {
                //dump($config->getId()." = ".strval($config->getValue()));
                $session->set($config->getId(), strval($config->getValue()));
            }
            
            // Utilisateur en cours
            $curentuserid=0;
            $token = $this->token_storage->getToken();
            if(!$token) return;
            $curentuser=$token->getUser();

            // Roles actif
            if($curentuser=="anon.") $roles=[];
            else $roles=$curentuser->getRoles();

            // Masteridentity
            $masteridentity  =$this->container->getParameter('masteridentity');
            $session->set('masteridentity',$masteridentity);

            // mode_auth
            $mode_auth  =$this->container->getParameter('mode_auth');
            $session->set('mode_auth',$mode_auth);

            // App activate
            $app=[];
            $app["importuser_activate"]                 =($masteridentity=="SQL");
            
            $app["portal_activate"]                     =$this->container->getParameter('portal_activate');
            $app["cron_activate"]                       =$this->container->getParameter('cron_activate');
            $app["module_activate"]                     =$this->container->getParameter('module_activate');
            $app["page_activate"]                       =$this->container->getParameter('page_activate');
            $app["item_activate"]                       =$this->container->getParameter('item_activate');
            $app["alert_activate"]                      =$this->container->getParameter('alert_activate');
            $app["calendar_activate"]                   =$this->container->getParameter('calendar_activate');
            $app["blog_activate"]                       =$this->container->getParameter('blog_activate');
            $app["flux_activate"]                       =$this->container->getParameter('flux_activate');
            $app["notice_activate"]                     =$this->container->getParameter('notice_activate');
            $app["syncenvole_activate"]                 =$this->container->getParameter('syncenvole_activate');
            $app["activate_widlimesurvey"]              =$this->container->getParameter('activate_widlimesurvey');
            $app["activate_widmoodle"]                  =$this->container->getParameter('activate_widmoodle');
            $app["activate_widpiwik"]                   =$this->container->getParameter('activate_widpiwik');
            $app["activate_widwordpress"]               =$this->container->getParameter('activate_widwordpress');

            $app["widbalado_activate_syncenvole"]       =$this->container->getParameter('widbalado_activate_syncenvole');
            $app["widcdt_activate_syncenvole"]          =$this->container->getParameter('widcdt_activate_syncenvole');
            $app["widgepi_activate_syncenvole"]         =$this->container->getParameter('widgepi_activate_syncenvole');
            $app["widnextcloud_activate_syncenvole"]    =$this->container->getParameter('widnextcloud_activate_syncenvole');
            $app["widpiwik_activate_syncenvole"]        =$this->container->getParameter('widpiwik_activate_syncenvole');
            $app["widsacoche_activate_syncenvole"]      =$this->container->getParameter('widsacoche_activate_syncenvole');

            // Chargement de la sidebar
            $iconniveau01   = "fa ".$this->container->getParameter('iconniveau01');
            $labelsniveau01 = $this->container->getParameter('labelsniveau01');
            $labelniveau01  = $this->container->getParameter('labelniveau01');
            $session->set('labelniveau01',$labelniveau01);
            $session->set('labelsniveau01',$labelsniveau01);

            $viewniveau02   = $this->container->getParameter('viewniveau02');
            $iconniveau02   = "fa ".$this->container->getParameter('iconniveau02');
            $labelsniveau02 = $this->container->getParameter('labelsniveau02');
            $labelniveau02  = $this->container->getParameter('labelniveau02');
            $session->set('viewniveau02',$viewniveau02);
            $session->set('labelniveau02',$labelniveau02);
            $session->set('labelsniveau02',$labelsniveau02);

            $moderegistration  =$this->container->getParameter('moderegistration');
            if($masteridentity!="SQL") $moderegistration="none";


            if(in_array("ROLE_MODO",$roles)) {
                $request = $event->getRequest();
                $route  = $request->attributes->get('_route');
                if($route!="cadoles_core_config"&&stripos($route,"_config")!==false&&stripos($route,"cadoles_core_config_file")===false) {
                    $permmodoprofil=$curentuser->getPermmodoprofil();

                    if(stripos($route,"cadoles_core_config_logo")!==false) $route="cadoles_portal_config_page";
                    if(stripos($route,"cadoles_core_config_header")!==false) $route="cadoles_portal_config_page";
                    
                    if(stripos($route,"cadoles_portal_config_panelwidget")!==false) $route="cadoles_portal_config_page";
                    if(stripos($route,"cadoles_portal_config_pagewidget")!==false) $route="cadoles_portal_config_page";
                    if(stripos($route,"cadoles_portal_config_bookmark")!==false) $route="cadoles_portal_config_page";
                    if(stripos($route,"cadoles_portal_config_slide")!==false) $route="cadoles_portal_config_page";
                    if(stripos($route,"cadoles_core_config_file")!==false) $route="cadoles_portal_config_page";
                    
                    if(stripos($route,"cadoles_portal_config_itemcategory")!==false) $route="cadoles_portal_config_item";
                    if(stripos($route,"cadoles_portal_config_alertcategory")!==false) $route="cadoles_portal_config_alert";
                    if(stripos($route,"cadoles_portal_config_calendarevent")!==false) $route="cadoles_portal_config_calendar";
                    if(stripos($route,"cadoles_portal_config_blogarticle")!==false) $route="cadoles_portal_config_blog";
                    if(stripos($route,"cadoles_portal_config_blogcomment")!==false) $route="cadoles_portal_config_blog";
                    if(stripos($route,"cadoles_portal_config_projecttask")!==false) $route="cadoles_portal_config_project";
                    if(stripos($route,"cadoles_cron_config")!==false) $route="cadoles_cron_config";

                    $tbroute=explode("_",$route);
                    $route =(isset($tbroute[0])?$tbroute[0]:"");
                    $route.=(isset($tbroute[1])?"_".$tbroute[1]:"");
                    $route.=(isset($tbroute[2])?"_".$tbroute[2]:"");
                    $route.=(isset($tbroute[3])?"_".$tbroute[3]:"");
                    
                    $permmodo = $this->em->getRepository("CadolesCoreBundle:PermModo")->findOneBy(['permmodoprofil'=>$permmodoprofil,'route'=> $route, "visible"=>true]);
                    if(!$permmodo) die('Permission denied');
                }
            }
            
            $sidebar=array();
            $nvs1 = $this->em->getRepository("CadolesCoreBundle:Sidebar")->findBy(array('parent'=> NULL), array('roworder' => 'ASC'));
            foreach($nvs1 as $nv1) {
                if($this->haveRole($curentuser,$roles,$nv1->getPermission(),$nv1->getPath())) {
                    $sidebar[$nv1->getRoworder()] = array(
                        "fonticon"  => $nv1->getFonticon(),
                        "label"     => $nv1->getLabel(),
                        "path"      => $nv1->getPath(),
                    );

                    if($nv1->getAppactivate()!=""&&!$app[$nv1->getAppactivate()]) {
                        unset($sidebar[$nv1->getRoworder()]);
                        continue;
                    }

                    if($nv1->getPath()=="cadoles_core_config_niveau01") {
                        $sidebar[$nv1->getRoworder()]["label"]=$labelsniveau01;
                        $sidebar[$nv1->getRoworder()]["fonticon"]=$iconniveau01;
                    }
                    if($nv1->getPath()=="cadoles_core_config_niveau02") {
                        if(!$viewniveau02) 
                            unset($sidebar[$nv1->getRoworder()]);
                        else {
                            $sidebar[$nv1->getRoworder()]["label"]=$labelsniveau02;
                            $sidebar[$nv1->getRoworder()]["fonticon"]=$iconniveau02;
                        }
                    }
                    if($nv1->getPath()=="cadoles_core_config_whitelist") {
                        if($moderegistration=="none")
                            unset($sidebar[$nv1->getRoworder()]);
                    }

                    foreach($nv1->getChilds() as $nv2) {
                 
                        if($this->haveRole($curentuser,$roles,$nv2->getPermission(),$nv2->getPath())) {
                            $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()] = array (
                                "fonticon"  => $nv2->getFonticon(),
                                "label"     => $nv2->getLabel(),
                                "path"      => $nv2->getPath(),
                            );

                            if($nv2->getPath()=="cadoles_core_config_niveau01") {
                                $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["label"]=$labelsniveau01;
                                $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["fonticon"]=$iconniveau01;
                            }


                            if($nv2->getPath()=="cadoles_core_config_niveau02") {
                                if(!$viewniveau02)
                                    unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]);
                                else {
                                    $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["label"]=$labelsniveau02;
                                    $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["fonticon"]=$iconniveau02;
                                }
                            }
                            if($nv2->getPath()=="cadoles_core_config_whitelist") {
                                if($moderegistration=="none")
                                    unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]);
                            }
                            if($nv2->getPath()=="cadoles_core_config_registration") {
                                if($moderegistration=="none") 
                                    unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]);
                            }

                            if($nv2->getAppactivate()!=""&&!$app[$nv2->getAppactivate()]) {
                                unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]);
                            }

                            foreach($nv2->getChilds() as $nv3) {
                                if($this->haveRole($curentuser,$roles,$nv3->getPermission(),$nv3->getPath())) {
                                    $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()] = array (
                                        "fonticon"  => $nv3->getFonticon(),
                                        "label"     => $nv3->getLabel(),
                                        "path"      => $nv3->getPath(),
                                    );

                                    if($nv3->getPath()=="cadoles_core_config_niveau01") {
                                        $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]["label"]=$labelsniveau01;
                                        $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]["fonticon"]=$iconniveau01;
                                    }   
                                    if($nv3->getPath()=="cadoles_core_config_niveau02") {
                                        if(!$viewniveau02)
                                            unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]);
                                        else {
                                            $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]["label"]=$labelsniveau02;
                                            $sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]["fonticon"]=$iconniveau02;
                                        }
                                    }  
                                    if($nv3->getPath()=="cadoles_core_config_whitelist") {
                                        if($moderegistration=="none"||$moderegistration=="byuser") 
                                            unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]);
                                    }

                                    if($nv3->getPath()=="cadoles_core_config_registration") {
                                        if($moderegistration=="none") 
                                            unset($sidebar[$nv1->getRoworder()]["childs"][$nv2->getRoworder()]["childs"][$nv3->getRoworder()]);
                                    }
                                }
                            }
                        }
                    }

                    if(is_null($sidebar[$nv1->getRoworder()]["path"])&&!isset($sidebar[$nv1->getRoworder()]["childs"]))
                        unset($sidebar[$nv1->getRoworder()]);
                } 
            }
            $session->set('sidebar', $sidebar);

            if($app["portal_activate"]) {
                $session->set('cancreatepage',false);
                $session->set('cancreatecalendar',false);
                $session->set('cancreateblog',false);
                $session->set('cancreateproject',false);
                $session->remove("sublogo");

                if($curentuser!="anon.") {
                    $groups=$curentuser->getGroups();
                    foreach($groups as $usergroup) {
                        $group=$usergroup->getGroup();
                        if($group->getFgcancreatepage()) $session->set('cancreatepage',true);
                        if($group->getFgcancreatecalendar()) $session->set('cancreatecalendar',true);
                        if($group->getFgcancreateblog()) $session->set('cancreateblog',true);
                        if($group->getFgcancreateproject()) $session->set('cancreateproject',true);
                    }

                    $niveau01=$curentuser->getNiveau01();
                    if($niveau01->getShowsubappname()) 
                        $session->set("subappname", $niveau01->getLabel());

                    if(!is_null($niveau01->getLogo()))
                        $session->set("sublogo", $niveau01->getLogo());

                    if(!is_null($niveau01->getHeader()))
                        $session->set("header", $niveau01->getHeader()); 

                    if(!is_null($niveau01->getColormain()))
                        $session->set("colormain", $niveau01->getColormain());                         

                    if(!is_null($niveau01->getFontcolorhover()))
                        $session->set("fontcolorhover", $niveau01->getFontcolorhover());                         

                    if(!is_null($niveau01->getColorbody()))
                        $session->set("colorbody", $niveau01->getColorbody());                         

                    if(!is_null($niveau01->getFontfacebody()))
                        $session->set("fontfacebody", $niveau01->getFontfacebody());                         

                    if(!is_null($niveau01->getFontfacetitle()))
                        $session->set("fontfacetitle", $niveau01->getFontfacetitle());                         

                        
                }
            }        

            // Calcul des couleurs
            $color = $this->container->get('cadoles.core.service.color');
            $color->setColor();
            
            if($curentuser!="anon.") {
                // Préférence
                $preference=$curentuser->getPreference();
                if(is_array($preference)) {
                    // Préférence header
                    if(array_key_exists("fgheader",$preference)) {
                        $fgheader=($preference["fgheader"][0]=="true");
                        $session->set("fgheader", $fgheader);
                    }

                    // Préférence header
                    if(array_key_exists("pagebookmark",$preference)) {
                        $pagebookmark=$preference["pagebookmark"][0];
                        $session->set("pagebookmark", $pagebookmark);
                    }
                }

                // Visite                
                $now=new \DateTime();
                if(!$curentuser->getVisitedate()) {
                    $curentuser->setVisitedate($now);
                    $curentuser->setVisitecpt($curentuser->getVisitecpt()+1);
                    $this->em->persist($curentuser);
                    $this->em->flush();                    
                }
                else {
                    $visitedate=clone $curentuser->getVisitedate();
                    $visitedate->add(new \DateInterval("PT1H"));
                    if($visitedate<$now) {
                        $curentuser->setVisitedate($now);
                        $curentuser->setVisitecpt($curentuser->getVisitecpt()+1);
                        $this->em->persist($curentuser);
                        $this->em->flush();                    
                    }
                }
            }
        }
    }
