<?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 CalendareventRepository extends EntityRepository
{ 
    public function getCalendareventByDate($calendar,$start,$end)
    {
        $calendarevents=$this->createQueryBuilder('calendarevent')
                             ->where('calendarevent.calendar=:calendar')
                             ->andWhere('calendarevent.start>=:start')
                             ->andWhere('calendarevent.end<=:end')
                             ->setParameter('calendar',$calendar)
                             ->setParameter('start',$start)
                             ->setParameter('end',$end)
                             ->OrderBy('calendarevent.start', 'ASC')   
                             ->getQuery()->getResult();
        
        return $calendarevents;
    }

    public function getCalendareventShareByDate($user,$start,$end)
    {    
        // Event partagées
        $calendareventshared=[];
        if($user) {
            $calendareventshared=$this->createQueryBuilder('calendarevent')
                    ->andWhere('calendarevent.start>=:start')
                    ->andWhere('calendarevent.end<=:end')  

                    ->from('CadolesPortalBundle:Calendar','calendar')
                    ->andWhere('calendarevent.calendar=calendar')
                    ->andWhere('calendar.user != :user')
                    ->andWhere('calendar.user is not null')

                    ->from('CadolesCoreBundle:Group','groupe')
                    ->andWhere('groupe.fgcanshare=:fgcanshare')
                    ->andWhere('groupe MEMBER OF calendarevent.groups')

                    ->from('CadolesCoreBundle:UserGroup','usergroupe')
                    ->andWhere('groupe=usergroupe.group')
                    ->andWhere('usergroupe.user=:user')

                    ->from('CadolesCoreBundle:UserGroup','proprio')
                    ->andWhere('proprio.group=groupe')
                    ->andWhere('proprio.user=calendar.user')
 
                    ->setParameter('fgcanshare',true)
                    ->setParameter('user',$user)
                    ->setParameter('start',$start)
                    ->setParameter('end',$end)

                    ->orderBy('calendarevent.start', 'ASC')                  
                    ->getQuery()->getResult();
        }
        
        return $calendareventshared;
    }

    public function getCalendareventGroupsShareByDate($user,$start,$end)
    {    
        // Event partagées
        $calendareventshared=[];
        if($user) {
            $calendareventshared=$this->createQueryBuilder('calendarevent')
                    ->andWhere('calendarevent.start>=:start')
                    ->andWhere('calendarevent.end<=:end')  

                    ->from('CadolesPortalBundle:Calendar','calendar')
                    ->andWhere('calendarevent.calendar=calendar')

                    ->from('CadolesCoreBundle:Group','groupe')
                    ->andWhere('groupe.fgcanshare=:fgcanshare')
                    ->andWhere('groupe MEMBER OF calendarevent.groups')

                    ->from('CadolesCoreBundle:UserGroup','usergroupe')
                    ->andWhere('groupe=usergroupe.group')
                    ->andWhere('usergroupe.user=:user')

                    ->setParameter('fgcanshare',true)
                    ->setParameter('user',$user)
                    ->setParameter('start',$start)
                    ->setParameter('end',$end)

                    ->orderBy('calendarevent.start', 'ASC')                  
                    ->getQuery()->getResult();
        }
        
        return $calendareventshared;
    }

    public function getUserCalendarevents($user,$sessioncolor,$usage,$group,&$firstcalendar) {
        $em=$this->getEntityManager();

        // On récupère soit les calendriers du group en cours soit l'ensemble des calendriers de l'utilisateur
        if($usage=="group") {
            $calendars=$em->getRepository("CadolesPortalBundle:Calendar")->getCalendarsGroup($user,$group);
            if($calendars) $firstcalendar=$calendars[0]->getId();
        }
        else {
            $em->getRepository("CadolesPortalBundle:Calendar")->getCalendarsUser($user,$calendarssuser,$calendarsadmin,$calendarsshared);
            $calendars=array_merge($calendarssuser,$calendarsadmin->toArray(),$calendarsshared); 
            $firstcalendar="all";
        }

        // Début & fin
        $start=new \DateTime();
        $start->setTime(0,0);

        $end=new \DateTime();
        $end->setTime(0,0);
        $end->add(new \DateInterval('P3M'));
        $end->modify('last day of this month');

        $events=[];
        $eventids=[];

        foreach($calendars as $calendar) {
            $calendarevents = $em->getRepository("CadolesPortalBundle:Calendarevent")->getCalendareventByDate($calendar,$start,$end);

            foreach($calendarevents as $calendarevent) {
                $tmp=[];
                $tmp['id']            = strval($calendarevent->getId());
                $tmp['title']         = $calendarevent->getName();
                $tmp['description']   = $calendarevent->getDescription();
                $tmp['start']         = $calendarevent->getStart();
                $tmp['end']           = $calendarevent->getEnd();
                $tmp['color']         = "#".(is_null($calendar->getColor())?$sessioncolor:$calendar->getColor());
                $tmp['allDay']        = $calendarevent->getAllday();
                $tmp['calendar']      = $calendar->getId();
                $tmp['name']          = $calendar->getName();
                $tmp['editable']      = $calendar->getCanupdate();
                
                // Si évènement sur la journée on enlève une 1 seconde à la date de fin
                if($tmp['allDay'])
                    $tmp['end']->sub(new \DateInterval('PT1S'));

                array_push($events,$tmp);
                array_push($eventids,$tmp["id"]);

            }
        }

        // On récupére les évenement partagé de l'utilisateur
        if($user) {
            $calendarevents = $em->getRepository("CadolesPortalBundle:Calendarevent")->getCalendareventGroupsShareByDate($user,$start,$end);
            foreach($calendarevents as $calendarevent) {
                if($usage=="group") {
                    if(!$calendarevent->getGroups()->contains($groupentity)) continue;
                }

                $tmp=[];
                $tmp['id']            = strval($calendarevent->getId());
                $tmp['title']         = $calendarevent->getName();
                $tmp['description']   = $calendarevent->getDescription();
                $tmp['start']         = $calendarevent->getStart();
                $tmp['end']           = $calendarevent->getEnd();
                $tmp['color']         = "#".(is_null($calendar->getColor())?$sessioncolor:$calendar->getColor());
                $tmp['allDay']        = $calendarevent->getAllday();
                $tmp['calendar']      = $calendar->getId();
                $tmp['name']          = $calendar->getName();
                $tmp['editable']      = $calendar->getCanupdate();

                // Si évènement sur la journée on enlève une 1 seconde à la date de fin
                if($tmp['allDay'])
                    $tmp['end']->sub(new \DateInterval('PT1S'));

                if(!in_array($tmp['id'],$eventids)) {
                    array_push($events,$tmp);
                    array_push($eventids,$tmp["id"]);
                }
            }
        }

        // On récupère les taches associé à l'utilisateur
        if($user) {
            if($usage=="group") {
                $projects=$em->getRepository("CadolesPortalBundle:Project")->getProjectsGroup($user,$group);
                if($projects) $firstproject=$projects[0]->getId();
            }
            else {
                $em->getRepository("CadolesPortalBundle:Project")->getProjectsUser($user,$projectssuser,$projectsadmin,$projectsshared);
                $projects=array_merge($projectssuser,$projectsadmin->toArray(),$projectsshared); 
            }  
            
            foreach($projects as $project) {
                $projecttasks = $em->getRepository("CadolesPortalBundle:Projecttask")->getProjectTasksByDate($project,$user,$start,$end);

                foreach($projecttasks as $projecttask) {
                    $tmp=[];
                    $tmp['id']            = "TASK".strval($projecttask->getId());
                    $tmp['title']         = $projecttask->getName();
                    $tmp['description']   = $projecttask->getDescription();
                    $tmp['start']         = $projecttask->getEnd();
                    $tmp['end']           = $projecttask->getEnd();
                    $tmp['color']         = "#".$sessioncolor;
                    $tmp['allDay']        = true;
                    $tmp['calendar']      = $project->getId();
                    $tmp['name']          = $project->getName()." - Tache";
                    $tmp['editable']      = false;
                       
                    array_push($events,$tmp);
                    array_push($eventids,$tmp["id"]);
    
                }
            }            
        }
        return $events;
    }
}
