<?php

namespace App\Event;

use Doctrine\ORM\EntityManager;
use App\Entity\Group;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use App\Service\LdapService;

class SyncGroup implements EventSubscriber
{
    protected $container;
    protected $em;
    protected $ldap;
    protected $shouldSync;
    protected $oldid;
    protected $baseGroup;

    public function __construct($container, EntityManager $em, LdapService $ldap) {
        $this->container = $container;
        $this->em = $em;
        $this->ldap = $ldap;

        $this->shouldSync = true;
    }

    public function getSubscribedEvents()
    {
        return array(
            'postPersist',
            'preUpdate',
            'postUpdate',
            'preRemove'
        );
    }

    public function preUpdate(PreUpdateEventArgs $args) {

        $entity = $args->getEntity();

        if(!($entity instanceof Group)) return;

        // Synchronisation uniquement si changement de valeur
        $this->shouldSync = $args->hasChangedField('label') ||
                            $args->hasChangedField('description') ||
                            $args->hasChangedField('owner') ||
                            $args->hasChangedField('email') ||
                            $args->hasChangedField('fgcanshare');
        
        if($args->hasChangedField('label')) $this->oldid=$args->getOldValue('label');
    }

    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        // On met à jour/créé la fiche de l'utilisateur dans l'annuaire
        if ($entity instanceof Group && $this->shouldSync) {
            $this->upsertGroup($entity);
        }
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        // On créait une fiche pour l'usager dans l'annuaire
        if ($entity instanceof Group) {
            $this->upsertGroup($entity);
        }
    }

    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if ($entity instanceof Group) {
            $this->removeGroup($entity);
        }
    }

    public function removeGroup($group) {
        // Synchonisation LDAP
        if($this->ldap->isEnabled()) {
            // On recherche dans l'annuaire
            $criteria = '(cn='.$group->getLabel().')';
            $subbranch= $this->baseGroup;
            $results = $this->ldap->search($criteria, array('cn'), $subbranch);

            if(count($results)) {
                $this->ldap->deleteGroup($group);
            }
        }  
        
        // Synchronisation Onlyoffice
        /*
        $only = $this->container->get('cadoles.core.service.only');
        if($only->isEnabled()) {
            $only->delGroup($group);
        } 
        */         
    }

    public function upsertGroup($group, $force = false)
    {
        // Synchonisation LDAP
        if($this->ldap->isEnabled()) {
            // On recherche dans l'annuaire
            if(isset($this->oldid))
                $criteria = '(cn='.$this->oldid.')';
            else
                $criteria = '(cn='.$group->getLabel().')';

            $subbranch=$this->baseGroup;
            $results = $this->ldap->search($criteria, array('cn'), $subbranch);

            // Mise à jour si elle existe
            if(count($results) > 0) {
                $this->ldap->modifyGroup($group,$this->oldid);
            }
            // Sinon création de la fiche
            else {
                $this->ldap->addGroup($group);
            }
        }   
        
        // Synchronisation Onlyoffice
        /*
        $only = $this->container->get('cadoles.core.service.only');
        if($only->isEnabled()) {
            $only->syncGroup($group,$this->oldid);
        } 
        */       
    }

    public function getBaseGroup() {
        return $this->baseGroup;
    }

    public function setBaseGroup($baseGroup) {
        $this->baseGroup = $baseGroup;
        return $this;
    }    
}
