<?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 BlogRepository extends EntityRepository
{

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

        
        // Permission sur les blogs
        if($blogsshared) {
            foreach($blogsshared as $blogshared) {
                $blogshared->setCanupdate(false);
                $blogshared->setCanadd($this->getInwriter($user,$blogshared));
            }
        }

        return $blogsshared;
    }

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

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

        // blogs partagées
        $blogsshared=[];
        /*
        if($user) {
            $blogsshared=$this->createQueryBuilder('blog')
                    ->from('CadolesCoreBundle:Group','g')
                    ->from('CadolesCoreBundle:UserGroup','ug')
                    ->from('CadolesCoreBundle:UserGroup','proprio')
                    ->where('g.fgcanshare=:fgcanshare')
                    ->andWhere('g=ug.group')
                    ->andWhere('ug.user=:user')
                    ->andWhere('g MEMBER OF blog.groups')
                    ->andWhere('blog.user != :user')
                    ->andWhere('blog.user is not null')
                    ->andWhere('proprio.user=blog.user')
                    ->andWhere('proprio.group=g')
                    ->setParameter('fgcanshare',true)
                    ->setParameter('user',$user)
                    ->addOrderBy('blog.name', 'ASC')                    
                    ->getQuery()->getResult();
        }
        
        // Permission sur les blogs
        if($blogsshared) {
            foreach($blogsshared as $blogshared) {
                $blogshared->setCanupdate(false);
                $blogshared->setCanadd($this->getInwriter($user,$blogshared));
            }
        }
        */

        // Initialisation du calcul des blogs
        $blogsadmin=new ArrayCollection();

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

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

        // Permission sur les blogs
        foreach($blogsadmin as $blogadmin) {
            $blogadmin->setCanupdate($this->getInmanager($user,$blogadmin));
            $blogadmin->setCanadd($this->getInwriter($user,$blogadmin));
        }     
    }

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

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

            // La blog est-elle dans les blogs associées au role de l'utilisateur ?
            foreach($roles as $role) {
                $qb = $this->createQueryBuilder("blog");
                $qb ->where($qb->expr()->like('blog.roles', $qb->expr()->literal("%$role%")))
                    ->andWhere("blog.id=:id")
                    ->andWhere("blog.user is null")
                    ->setParameter("id",$blog->getId());
                $inblogrole=$qb->getQuery()->getResult();
                if($inblogrole) $cansee=true;
            }   
            

            // La blog est-elle dans les blogs associées aux groupes de l'utilisateur ?
            foreach($groups as $group) {
                $qb = $this->createQueryBuilder("blog");
                $qb ->where(":group MEMBER OF blog.groups")
                    ->andWhere("blog.id=:id")
                    ->setParameter("id",$blog->getId())
                    ->setParameter("group",$group->getGroup());
                
                $inbloggroup=$qb->getQuery()->getResult();
                if($inbloggroup)  {
                    $cansee=true;

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

                        // Est-il gestionnaire du groupe
                        if($group->getRolegroup()>=90) $canupdate=true;
                    }
                }
            } 

            // utilisateur a-t-il la permission d'écriture
            $canadd=$this->getInwriter($user,$blog);
            
        }
    }

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

        if($user) {
            // Peut ecrire ceux qui sont déclaré comme écrivain
            $qb = $this->createQueryBuilder("blog");
            $qb ->andWhere("blog.id=:id")
                ->andwhere(':user MEMBER OF blog.writers')

                ->from('CadolesCoreBundle:User','user')
                ->andwhere("user=:user")
                
                ->from('CadolesCoreBundle:UserGroup','usergroup')
                ->andwhere('usergroup.group MEMBER OF blog.groups')
                ->andwhere('usergroup.user=:user')

                ->setParameter("id",$blog->getId())
                ->setparameter('user',$user);            

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

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

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

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

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

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


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

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

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

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

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


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