<?php
namespace Cadoles\CoreBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Ramsey\Uuid\Uuid;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Id\AssignedGenerator;

use Cadoles\CoreBundle\Entity\Group;
use Cadoles\CoreBundle\Entity\UserGroup;
use Cadoles\CoreBundle\Entity\PermModoProfil;
use Cadoles\CoreBundle\Entity\PermModo;

class InitDataCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            // the name of the command (the part after "bin/console")
            ->setName('Core:InitData')

            // the short description shown while running "php bin/console list"
            ->setDescription('Init Data for Core')

            // the full command description shown when running the command with
            // the "--help" option
            ->setHelp('This command Init Data for Core')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('');
        $output->writeln('CORE = Default Data');

        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        $masteridentity=$this->getContainer()->getParameter('masteridentity');
        $ldap_template = $this->getContainer()->getParameter('ldap_template');

		$finder = new Finder();
    	$finder->in('src/Cadoles/CoreBundle/Command/data');

        // Init 01 = ce qui templetisé
        $output->writeln('  > Parametres 01');
        $finder->name('core-init-01.sql');
    	foreach( $finder as $file ){
        	$content = $file->getContents();

            $stmt = $em->getConnection()->prepare($content);
            $stmt->execute();
    	}

        // Init 02 = ce qui est toujours le cas
        $output->writeln('  > Parametres 02');
        $finder->name('core-init-02.sql');
    	foreach( $finder as $file ){
        	$content = $file->getContents();

        	$stmt = $em->getConnection()->prepare($content);
        	$stmt->execute();
        }

        // Init country
        $output->writeln('  > Pays');
        $finder->name('country.sql');
        foreach( $finder as $file ){
            $content = $file->getContents();

            $stmt = $em->getConnection()->prepare($content);
            $stmt->execute();
            
        }

        // Init city
        $output->writeln('  > Villes');
        $finder->name('city.sql');
        foreach( $finder as $file ){
            $content = $file->getContents();

            $stmt = $em->getConnection()->prepare($content);
            $stmt->execute();
            
        }
        $stmt->closeCursor();

        // On s'assure que l'admin à un password et sinon on l'init à la valeur du genconfig
        $user=$em->getRepository('CadolesCoreBundle:User')->findOneBy(['username'=>'admin']);
        if($user&&empty($user->getPassword())) {
            $initpwdadmin=$this->getContainer()->getParameter('initpwdadmin');
            $output->writeln('  > Initialisation passsword admin / '.$initpwdadmin.' : pensez à modfier votre password après connexion');
            $user->setPassword($initpwdadmin);
            $em->persist($user);
            $em->flush();               
        }

        // On s'assure que le groupe 'Tout le Monde' existe
        $group=$em->getRepository('CadolesCoreBundle:Group')->findOneBy(array('fgall'=>true));
        if (!$group) {
            $output->writeln('  > Création du groupe Tout le Monde');
            $group = new Group();
            $group->setLabel("Tout le Monde");
            $group->setFgopen(false);
            $group->setFgall(true);
            $group->setFgtemplate(false);
            $group->setFgcanshare(false);
            $group->setFgcancreatepage(true);
            $group->setFgcancreateblog(true);
            $group->setFgcancreatecalendar(true);
            $group->setFgcancreateproject(true);
            $em->persist($group);
            $em->flush();            
        }

        $sub = $em->createQueryBuilder();
        $sub->select("usergroup");
        $sub->from("CadolesCoreBundle:UserGroup","usergroup");
        $sub->andWhere('usergroup.user = user.id');
        $sub->andWhere('usergroup.group = :groupid');

        $qb = $em->createQueryBuilder();
        $qb->select('user')
           ->from('CadolesCoreBundle:User','user')
           ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
           ->setParameter("groupid",$group->getId());
        $datas=$qb->getQuery()->getArrayResult();
        $nbusers=0;
        foreach($datas as $data) {
            $nbusers++;
            $user=$em->getRepository('CadolesCoreBundle:User')->find($data["id"]);
            $group=$em->getRepository('CadolesCoreBundle:Group')->findOneBy(array('fgall'=>true));

            $output->writeln("  $nbusers sur ".count($datas)." > Ratachement ".$user->getId()." ".$user->getUsername());
            $key = Uuid::uuid4();
            $usergroup=new UserGroup();
            $usergroup->setUser($user);
            $usergroup->setGroup($group);
            $usergroup->setKeyvalue($key);
            $usergroup->setRolegroup(0);            
            $em->persist($usergroup);
            $em->flush();             
            $em->clear();             
            //$user=$em->getRepository('CadolesCoreBundle:User')->find($data["id"]);
        }

        // On s'assure si masteridentity est à LDAP qu'au minimum un niveau01 possède un filtre LDAP
        if($masteridentity=="LDAP") {
            $niveau01=$em->createQueryBuilder()->select('n')->from('CadolesCoreBundle:Niveau01','n')->where('n.ldapfilter IS NOT NULL')->getQuery()->getResult();
            if(!$niveau01) {
                // Si ce n'est pas le cas on positionne un filtre ultra large sur le niveau01 de base
                $niveau01=$group=$em->getRepository('CadolesCoreBundle:Niveau01')->find(-100);

                if($ldap_template=="scribe")
                    $niveau01->setLdapfilter("(&(uid=*)(objectclass=inetOrgPerson)(!(description=Computer)))");
                else
                    $niveau01->setLdapfilter($this->getContainer()->getParameter('openldapreqniveau01'));
                
                $em->persist($niveau01);
                $em->flush();             
            }
        }

        // On s'assure si masteridentity est à SSO qu'au minimum un niveau01 possède un attribut
        if($masteridentity=="SSO") {
            $niveau01=$em->createQueryBuilder()->select('n')->from('CadolesCoreBundle:Niveau01','n')->where('n.attributes IS NOT NULL')->getQuery()->getResult();
            if(!$niveau01) {
                // Si ce n'est pas le cas on positionne un attribut ultra large sur le niveau01 de base
                $niveau01=$group=$em->getRepository('CadolesCoreBundle:Niveau01')->find(-100);
                $niveau01->setAttributes('{"username":"*"}');
               
                $em->persist($niveau01);
                $em->flush();             
            }
        }

        // Génération du profils de permissions modérateurs
        $metadata = $em->getClassMetaData('CadolesCoreBundle:PermModoProfil');
        $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
        $metadata->setIdGenerator(new AssignedGenerator());        

        $entityprofil = $em->getRepository('CadolesCoreBundle:PermModoProfil')->find(-100);
        if(!$entityprofil) {
            $entityprofil = new PermModoProfil();
            $entityprofil->setId(-100);
            $entityprofil->setName("Global");
            $em->persist($entityprofil);
            $em->flush();
        }

        // Affecter les permissions modérateurs sans profils sur le profils par défaut
        $entitys = $em->getRepository('CadolesCoreBundle:PermModo')->findBy(["permmodoprofil"=>null]);
        foreach($entitys as $entity) {
            $entity->setPermmodoprofil($entityprofil);
            $em->persist($entity);
            $em->flush();
        }

        // Affecter le profil modérateur par défaut aux modérateurs qui n'en ont pas
        $users = $em->getRepository('CadolesCoreBundle:User')->findBy(["role"=>"ROLE_MODO","permmodoprofil"=>null]);
        foreach($users as $user) {
            $user->setPermmodoprofil($entityprofil);
            $em->persist($user);
            $em->flush();
        }

        // Initialiser l'ensemble des profils modérateurs
        $entityprofils = $em->getRepository('CadolesCoreBundle:PermModoProfil')->findAll();
        foreach($entityprofils as $profil) {
            $this->addModeration($profil,'cadoles_core_config_commun',0);
            $this->addModeration($profil,'cadoles_core_config_theme',0);
            $this->addModeration($profil,'cadoles_core_config_datauser',0);
            $this->addModeration($profil,'cadoles_core_config_datausers',0);
            $this->addModeration($profil,'cadoles_core_config_whitelist',0);
            $this->addModeration($profil,'cadoles_core_config_niveau01',1);
            $this->addModeration($profil,'cadoles_core_config_niveau02',1);
            $this->addModeration($profil,'cadoles_core_config_group',1);
            $this->addModeration($profil,'cadoles_core_config_registration',1);
            $this->addModeration($profil,'cadoles_core_config_user',1);
            $this->addModeration($profil,'cadoles_portal_config_pagetemplate',1);
            $this->addModeration($profil,'cadoles_portal_config_page',1);
            $this->addModeration($profil,'cadoles_portal_config_item',1);
            $this->addModeration($profil,'cadoles_portal_config_alert',1);
            $this->addModeration($profil,'cadoles_portal_config_calendar',1);
            $this->addModeration($profil,'cadoles_portal_config_blog',1);
            $this->addModeration($profil,'cadoles_portal_config_project',1);
            $this->addModeration($profil,'cadoles_portal_config_flux',1);
            $this->addModeration($profil,'cadoles_portal_config_notice',1);
            $this->addModeration($profil,'cadoles_portal_config_icon',1);
            $this->addModeration($profil,'cadoles_portal_config_syncbalado',0);
            $this->addModeration($profil,'cadoles_portal_config_synccdt',0);
            $this->addModeration($profil,'cadoles_portal_config_syncgepiannu',0);
            $this->addModeration($profil,'cadoles_portal_config_syncgepisiecle',0);
            $this->addModeration($profil,'cadoles_portal_config_synclimesurvey',0);
            $this->addModeration($profil,'cadoles_portal_config_syncmoodle',0);
            $this->addModeration($profil,'cadoles_portal_config_syncnextcloud',0);
            $this->addModeration($profil,'cadoles_portal_config_syncsacoche',0);
            $this->addModeration($profil,'cadoles_portal_config_syncpiwik',0);
            $this->addModeration($profil,'cadoles_portal_config_syncwordpress',0);

            $this->addModeration($profil,'cadoles_core_config_statistic',1);
            $this->addModeration($profil,'cadoles_core_config_mailing',1);
            $this->addModeration($profil,'cadoles_core_config_importuser',0);
            $this->addModeration($profil,'cadoles_cron_config',0);
            $this->addModeration($profil,'cadoles_cron_config_log',0);
        }

        // Forcer le theme
        $force_theme=$this->getContainer()->getParameter('force_theme');
        if($force_theme) {

            // On force la configuration du theme
            $force_themename=$this->getContainer()->getParameter('force_themename');
            $config = $em->getRepository('CadolesCoreBundle:Config')->find("theme");
            if($config) {
                $config->setValue($force_themename);
                $em->persist($config);
                $em->flush();                 
            }

            // On enlève l'accès de la sidebar
            $sidebar = $em->getRepository('CadolesCoreBundle:Sidebar')->findOneBy(["path"=>"cadoles_core_config_theme"]);
            if($sidebar) {
                $em->remove($sidebar);
                $em->flush();                
            }
        }

        $output->writeln('');
    }

    protected static function determineKernelRootDir(Event $event) {
        $extra = $event->getComposer()->getPackage()->getExtra();
        $rootdir = rtrim(getcwd(), '/');
        return $rootdir . '/' . trim($extra['symfony-app-dir'], '/');
    }

    protected function addModeration($profil,$route,$visible) {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        $entity=$em->getRepository('CadolesCoreBundle:PermModo')->findOneBy(["route"=>$route,"permmodoprofil"=>$profil]);
        if(!$entity) {
            $entity=new PermModo();
            $entity->setRoute($route);
            $entity->setVisible($visible);
            $entity->setPermmodoprofil($profil);
            $em->persist($entity);
            $em->flush();            
        }
    }
}
