<?php

namespace Cadoles\PortalBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Cadoles\PortalBundle\Entity\Page;
use Cadoles\PortalBundle\Entity\Pagecategory;

class CalendarRepository extends EntityRepository
{

    // getCalendarsGroup
    // $user                = l'utilisateur en cours
    // $groupid             = id du group 
    
    public function getCalendarsGroup($user,$groupid)
    {
        $calendarsshared=$this->createQueryBuilder('calendar')
                ->from('CadolesCoreBundle:Group','g')
                ->andWhere('g MEMBER OF calendar.groups')
                ->andWhere('g.id=:id')
                ->setParameter('id',$groupid)
                ->addOrderBy('calendar.name', 'ASC')                    
                ->getQuery()->getResult();
        
        return $calendarsshared;
    }

    // getCalendarsUser
    // $user                = l'utilisateur en cours
    // &$calendarsuser      = les calendars de l'utilisateur
    // &$calendars          = les calendars système de l'utilistauer
    // &$calendarsshared    = les calendars partagées pour l'utilisateur
    
    public function getCalendarsUser($user,&$calendarsuser,&$calendarsadmin,&$calendarsshared)
    {
        // Profilage
        $roles=($user?$user->getRoles():["ROLE_ANONYME"]);
        $groups=($user?$user->getGroups():[]);

        // Récupération des calendars de l'utilisateur
        $calendarsuser=[];
        if($user) {
            $qb = $this->createQueryBuilder('calendar');
            $qb ->where("calendar.user=:user")
                ->setParameter("user",$user)
                ->addOrderBy('calendar.name', 'ASC');
            $calendarsuser=$qb->getQuery()->getResult();
        }
        
        // Permission sur les calendars
        if($calendarsuser) {
            foreach($calendarsuser as $calendaruser) {
                $calendaruser->setCanupdate(true);
                $calendaruser->setCanadd(true);
            }
        }

        // Pages partagées
        $calendarsshared=[];
        /*
        if($user) {
            $calendarsshared=$this->createQueryBuilder('calendar')
                    ->from('CadolesCoreBundle:Group','g')
                    ->from('CadolesCoreBundle:UserGroup','ug')
                    ->where('g.fgcanshare=:fgcanshare')
                    ->andWhere('g=ug.group')
                    ->andWhere('ug.user=:user')
                    ->andWhere('g MEMBER OF calendar.groups')
                    ->andWhere('calendar.user != :user')
                    ->andWhere('calendar.user is not null')
                    ->setParameter('fgcanshare',true)
                    ->setParameter('user',$user)
                    ->addOrderBy('calendar.name', 'ASC')                    
                    ->getQuery()->getResult();
        }
        */
        

        // Initialisation du calcul des calendars
        $calendarsadmin=new ArrayCollection();

        // Récupération des calendars par rôles
        foreach($roles as $role) {
            $qb = $this->createQueryBuilder("calendar");
            $qb ->where($qb->expr()->like('calendar.roles', $qb->expr()->literal("%$role%")))
                ->andWhere("calendar.user != :user or calendar.user is null")
                ->setParameter('user',$user);
            
            $calendarsroles=$qb->getQuery()->getResult();
            foreach($calendarsroles as $calendarrole) {
                if(!$calendarsadmin->contains($calendarrole)) $calendarsadmin->add($calendarrole);
            }
        }

        // Récupération des calendars par group
        foreach($groups as $group) {
            $qb = $this->createQueryBuilder("calendar");
            $qb ->where(":group MEMBER OF calendar.groups")
                ->andWhere("calendar.user != :user or calendar.user is null")
                ->setParameter('user',$user)
                ->setParameter("group",$group->getGroup());
            
            $calendarsgroups=$qb->getQuery()->getResult();
            foreach($calendarsgroups as $calendargroup) {
                if(!$calendarsadmin->contains($calendargroup)) $calendarsadmin->add($calendargroup);
            }
        }

        // Permission sur les calendars
        foreach($calendarsadmin as $calendaradmin) {
            $calendaradmin->setCanupdate($this->getInmanager($user,$calendaradmin));
            $calendaradmin->setCanadd($this->getInwriter($user,$calendaradmin));
        }            
    }

    public function getPermission($user,$calendar,&$cansee,&$canupdate,&$canadd) {
        // si calendar de l'utilisateur
        if($calendar->getUser()==$user&&!is_null($user)) {
            $cansee=true;
            $canupdate=true;
            $canadd=true;
        }
        else {
            $canupdate=false;
            $canadd=false;
            $cansee=false;

            // Profilage
            $roles=($user?$user->getRoles():["ROLE_ANONYME"]);
            $groups=($user?$user->getGroups():[]);


            // Le calendar est-il dans les calendars associées au role de l'utilisateur ?
            foreach($roles as $role) {
                $qb = $this->createQueryBuilder("calendar");
                $qb ->where($qb->expr()->like('calendar.roles', $qb->expr()->literal("%$role%")))
                    ->andWhere("calendar.id=:id")
                    ->andWhere("calendar.user is null")
                    ->setParameter("id",$calendar->getId());
                $incalendarrole=$qb->getQuery()->getResult();
                if($incalendarrole) $cansee=true;
            }   
            
            //  Le calendar est-il dans les calendars associées aux groupes de l'utilisateur ?
            foreach($groups as $group) {
                $qb = $this->createQueryBuilder("calendar");
                $qb ->where(":group MEMBER OF calendar.groups")
                    ->andWhere("calendar.id=:id")
                    ->setParameter("id",$calendar->getId())
                    ->setParameter("group",$group->getGroup());
                
                $incalendargroup=$qb->getQuery()->getResult();
                if($incalendargroup) {
                    $cansee=true;

                    // Est-il manager du groupe
                    if($group->getGroup()->getFgcanshare()) {
                        if($group->getRolegroup()>=90) $canupdate=true;
                        if($group->getRolegroup()>=50) $canadd=true;
                    }                    
                }
            }            
        }
    }

    public function getInwriter($user,$calendar) {
        $can=false;

        if($user) {
            // Peut ecrire ceux qui sont manager du groupe auquel est rattaché le calendar
            $qb = $this->createQueryBuilder("calendar");
            $qb ->andWhere("calendar.id=:id")
                ->from('CadolesCoreBundle:User','user')
                ->andwhere("user=:user")

                ->from('CadolesCoreBundle:UserGroup','usergroup')
                ->andwhere('usergroup.group MEMBER OF calendar.groups')
                ->andwhere('usergroup.user=user')
                ->andwhere('usergroup.rolegroup>=:role')

                ->from('CadolesCoreBundle:Group','groupe')
                ->andwhere('groupe=usergroup.group')
                ->andwhere('groupe.fgcanshare=:flag')

                ->setParameter("id",$calendar->getId())
                ->setParameter("role",50)
                ->setparameter('user',$user)
                ->setparameter('flag',true);


            $inblogwriters=$qb->getQuery()->getResult();
            
            if($inblogwriters) $can=true;     
        }
        
        return $can;
    } 

    public function getInmanager($user,$calendar) {
        $can=false;

        if($user) {
            // Peut ecrire ceux qui sont manager du groupe auquel est rattaché le calendar
            $qb = $this->createQueryBuilder("calendar");
            $qb ->andWhere("calendar.id=:id")
                ->from('CadolesCoreBundle:User','user')
                ->andwhere("user=:user")

                ->from('CadolesCoreBundle:UserGroup','usergroup')
                ->andwhere('usergroup.group MEMBER OF calendar.groups')
                ->andwhere('usergroup.user=user')
                ->andwhere('usergroup.rolegroup>=:role')

                ->from('CadolesCoreBundle:Group','groupe')
                ->andwhere('groupe=usergroup.group')
                ->andwhere('groupe.fgcanshare=:flag')

                ->setParameter("id",$calendar->getId())
                ->setParameter("role",90)
                ->setparameter('user',$user)
                ->setparameter('flag',true);


            $inblogwriters=$qb->getQuery()->getResult();
            
            if($inblogwriters) $can=true;     
        }
        
        return $can;
    }    
}
