<?php

namespace App\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\ArrayCollection;

class NoticeRepository extends EntityRepository
{
    // getNoticeToRead  
    public function getNoticeUser($user,$mustread=false)
    {
        // Profilage
        $roles=($user?$user->getRoles():["ROLE_ANONYME"]);
        $groups=($user?$user->getGroups():[]);

        // Initialisation du calcul des chartes
        $noticesnotorder=new ArrayCollection();

        // Récupération des chartes par rôles
        foreach($roles as $role) {
            $qb = $this->createQueryBuilder("notice");
            $qb ->where($qb->expr()->like('notice.roles', $qb->expr()->literal("%$role%")));
            if($mustread)
                $qb ->andWhere(':user NOT MEMBER OF notice.users')
                    ->andWhere('notice.mustread=true')
                    ->setParameter('user',$user);
            
            $noticesroles=$qb->getQuery()->getResult();
            foreach($noticesroles as $noticerole) {
                if(!$noticesnotorder->contains($noticerole)) $noticesnotorder->add($noticerole);
            }
        }

        // Récupération des pages par group
        foreach($groups as $group) {
            $qb = $this->createQueryBuilder("notice");
            $qb ->where(":group MEMBER OF notice.groups")
                ->setParameter("group",$group->getGroup());
            
            if($mustread)
                $qb ->andWhere(':user NOT MEMBER OF notice.users')
                ->andWhere('notice.mustread=true')
                ->setParameter('user',$user);

            $noticesgroups=$qb->getQuery()->getResult();
            foreach($noticesgroups as $noticegroup) {
                if(!$noticesnotorder->contains($noticegroup)) $noticesnotorder->add($noticegroup);
            }
        }

        return $noticesnotorder;
    }

    // getNoticeToRead  
    public function getNoticeToRead($user)
    {
        return $this->getNoticeUser($user,true);
    }
}
