<?php

namespace App\Repository;

use Doctrine\Common\Collections\ArrayCollection;
use App\Entity\UserGroup;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

class GroupRepository extends \Doctrine\ORM\EntityRepository
{
    /* Affectation des attributs calculés */
    public function calculateGroup($user,$attruser)
    {
        $groups = $this->_em->getRepository('App\Entity\Group')->findAll();
        $retgroups= new ArrayCollection();
        foreach($groups as $group) {
            if($group->getAttributes()) {
                
                $attgroup=json_decode($group->getAttributes(),true);

                foreach($attgroup as $key => $value) {
                    if(array_key_exists($key,$attruser)) {
                        if(is_array($attruser[$key])) {
                            foreach($attruser[$key] as $val) {
                                if($value=="*")
                                    $retgroups->add($group);
                                elseif($val==$value)
                                    $retgroups->add($group);
                            }
                        }
                        else {
                            if($value=="*")
                                $retgroups->add($group);
                            elseif($value==$attruser[$key])
                                $retgroups->add($group);
                        }
                    }
                }
            }
        }

        // Pour chaque groupe de l'utilisateur
        $usergroups=$user->getGroups();

        // On le détache des groupes auxquelles il n'appartient plus
        if($usergroups) {
            foreach($usergroups as $usergroup) {
                if($usergroup->getGroup()->getAttributes()!="") {
                    if(!$retgroups->contains($usergroup->getGroup())) {
                        $user->removeGroup($usergroup);
                    }
                }
            }
        }
        
        // On attache le user aux groupes
        foreach($retgroups as $retgroup) {
            $usergroup=$this->_em->getRepository('App\Entity\UserGroup')->findBy(["user"=>$user,"group"=>$retgroup]);
            if(!$usergroup) {
                $key = Uuid::uuid4();
                $usergroup=new UserGroup();
                $usergroup->setUser($user);
                $usergroup->setGroup($retgroup);
                $usergroup->setKeyvalue($key);
                $usergroup->setRolegroup(0);

                $this->_em->persist($usergroup);
                $this->_em->flush();                
            }
        }

        return $user;
    }

}
