<?php
namespace Cadoles\CoreBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\ORM\EntityManager;

use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Id\AssignedGenerator;

use Cadoles\CoreBundle\Entity\Script;
use Cadoles\CoreBundle\Entity\User;
use Cadoles\PortalBundle\Entity\Project;
use Cadoles\PortalBundle\Entity\Pagewidget;

global $bdd01;
global $config;

class ScriptCommand extends Command
{
    private $container;
    private $em;
    private $output;
    private $filesystem;
    private $rootlog;

    protected function configure()
    {
        $this
            ->setName('Core:Script')
            ->setDescription('Lauch Script')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->container    = $this->getApplication()->getKernel()->getContainer();
        $this->em           = $this->container->get('doctrine')->getEntityManager();
        $this->output       = $output;
        $this->filesystem   = new Filesystem();
        $this->rootlog      = $this->container->get('kernel')->getRootDir()."/../var/logs/";


        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"visibletrue"]);
        if(!$script) {
            $this->writeln("== SCRIPT = visibletrue");
            $this->visibletrue();

            $script=new Script();
            $script->setName("visibletrue");
            $this->em->persist($script);
            $this->em->flush();
            $this->writeln("");                  
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"setusersniveau"]);
        if(!$script) {
            $this->writeln("== SCRIPT = setusersniveau");
            $this->setusersniveau();

            $script=new Script();
            $script->setName("setusersniveau");
            $this->em->persist($script);
            $this->em->flush();
            $this->writeln("");                  
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"setfgcancreateproject"]);
        if(!$script) {
            $this->writeln("== SCRIPT = setfgcancreateproject");
            $this->setfgcancreateproject();

            $script=new Script();
            $script->setName("setfgcancreateproject");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"createproject"]);
        if(!$script) {
            $this->writeln("== SCRIPT = createproject");
            $this->createproject();

            $script=new Script();
            $script->setName("createproject");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"createthumbmini"]);
        if(!$script) {
            $this->writeln("== SCRIPT = createthumbmini");
            $this->createthumbmini();

            $script=new Script();
            $script->setName("createthumbmini");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"createwidgetproject"]);
        if(!$script) {
            $this->writeln("== SCRIPT = createwidgetproject");
            $this->createwidgetproject();
    
            $script=new Script();
            $script->setName("createwidgetproject");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"renamegroup"]);
        if(!$script) {
            $this->writeln("== SCRIPT = renamegroup");
            $this->renamegroup();
            
            $script=new Script();
            $script->setName("renamegroup");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }


        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"rolegroup"]);
        if(!$script) {
            $this->writeln("== SCRIPT = rolegroup");
            $this->rolegroup();
            
            $script=new Script();
            $script->setName("rolegroup");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"userdefaultmissing"]);
        if(!$script) {
            $this->writeln("== SCRIPT = userdefaultmissing");
            $this->userdefaultmissing();
            
            $script=new Script();
            $script->setName("userdefaultmissing");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"updateorthographe01"]);
        if(!$script) {
            $this->writeln("== SCRIPT = updateorthographe01");
            $this->updateorthographe01();
            
            $script=new Script();
            $script->setName("updateorthographe01");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"updateorthographe02"]);
        if(!$script) {
            $this->writeln("== SCRIPT = updateorthographe02");
            $this->updateorthographe02();
            
            $script=new Script();
            $script->setName("updateorthographe02");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }

        if($this->container->getParameter('ldap_template')=="scribe") {
            $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"purgepageprofil"]);
            if(!$script) {
                $this->writeln("== SCRIPT = purgepageprofil");
                $this->purgepageprofil();
                
                $script=new Script();
                $script->setName("purgepageprofil");
                $this->em->persist($script);
                $this->em->flush();                  
                $this->writeln("");
            }
        }


        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"setfgpreference"]);
        if(!$script) {
            $this->writeln("== SCRIPT = setfgpreference");
            $this->setfgpreference();

            $script=new Script();
            $script->setName("setfgpreference");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }     
        
        $script=$this->em->getRepository("CadolesCoreBundle:Script")->findOneBy(["name"=>"renamesidebar01"]);
        if(!$script) {
            $this->writeln("== SCRIPT = renamesidebar01");
            $this->renamesidebar("cadoles_core_config_datausers","Aperçu Utilisateur");

            $script=new Script();
            $script->setName("renamesidebar01");
            $this->em->persist($script);
            $this->em->flush();                  
            $this->writeln("");
        }        


        return 1;
    }

    private function visibletrue() {
        $users = $this->em->getRepository('CadolesCoreBundle:User')->findAll();
        foreach($users as $user) {
            if(!$user->getVisible()) {
                $this->writeln($user->getUsername());
                
                $user->setVisible(true);
                $this->em->persist($user);
                $this->em->flush();               
            }
        }        
    }

    private function setusersniveau() {
        $users = $this->em->getRepository('CadolesCoreBundle:User')->findAll();
        foreach($users as $user) {
            $this->writeln($user->getUsername());
            
            $user->setLabelniveau01($user->getNiveau01()->getLabel());
            $user->setLabelniveau02(($user->getNiveau02()?$user->getNiveau02()->getLabel():null));

            $this->em->persist($user);
            $this->em->flush();               
        }        
    }

    private function setfgcancreateproject() {
        $group=$this->em->getRepository('CadolesCoreBundle:Group')->findOneBy(array('fgall'=>true));
        if ($group) {
            $group->setFgcancreateproject(true);
            $this->em->persist($group);
            $this->em->flush();            
        }  
    }

    private function createproject() {
        $groups=$this->em->getRepository('CadolesCoreBundle:Group')->findBy(array('fgcanshare'=>true));
        foreach($groups as $group) {
            // On regarde s'il a au moins un project
            if($group->getProjects()->isEmpty()) {
                $project=new Project();

                $project->setName($group->getLabel());
                $project->addGroup($group);
                $project->setUser($group->getOwner());

                $this->em->persist($project);
                $this->em->flush();                  
            }            
        }
    }

    private function createthumbmini() {
        $directory=$this->container->get('kernel')->getRootDir()."/../uploads/file";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->directories()->exclude("thumb")->exclude("thumbmini");

            foreach (iterator_to_array($finder) as $rep) {
                $finder2 = new Finder();
                if($fs->exists($rep."/thumb")) { 
                    $finder2->sortByName()->in($rep."/thumb");
                    
                    foreach ($finder2 as $file) {
                        if(!$fs->exists($rep."/thumbmini/".$file->getRelativePathname())) {
                            $this->writeln($file->getRelativePathname());
                            $fs->mkdir($rep."/thumbmini");
                            $fs->copy($rep."/thumb/".$file->getRelativePathname(),$rep."/thumbmini/".$file->getRelativePathname());
                            $max_width=60;
                            $width = $this->getWidth($rep."/thumbmini/".$file->getRelativePathname());
                            $height = $this->getHeight($rep."/thumbmini/".$file->getRelativePathname());                    
                            $scale = $max_width/$width;
                            $this->resizeImage($rep."/thumbmini/".$file->getRelativePathname(),$width,$height,$scale);     
                            $fs->chown($rep."/thumbmini/".$file->getRelativePathname(), 'www-data');                       
                        }
                    }
                }
            }
        }
    }

    private function createwidgetproject(){
        
        $entityPage = $this->em->getRepository('CadolesPortalBundle:Page')->find(-110);
        if($entityPage) {
            $fields=["fields"=>[]];
        
            $metadata = $this->em->getClassMetaData('CadolesPortalBundle:Pagewidget');
            $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO);
            $pages=$this->em->getRepository('CadolesPortalBundle:Page')->findBy(["page"=>$entityPage]);
            foreach($pages as $page) {
                $this->addWidget2Page($page,-1800,"R1C1",1,"Taches du groupe",true,$fields);  
            }

            $metadata = $this->em->getClassMetaData('CadolesPortalBundle:Pagewidget');
            $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
            $metadata->setIdGenerator(new AssignedGenerator());
            $this->addWidget(-145,$entityPage,-1800,"R1C1",1,"Taches du groupe",true,$fields);  
   
        }
    }


    private function renamegroup(){
        
        $groups = $this->em->getRepository('CadolesCoreBundle:Group')->findAll();
        foreach($groups as $group) {
            // Si présence d'un = dans le label
            if(stripos($group->getLabel(),"=")!==false) {
                $newname=str_replace("=","-",$group->getLabel());

                $this->writeln("Renommer groupe = ".$group->getLabel());

                // Renommer les pages 
                $pages = $this->em->getRepository('CadolesPortalBundle:Page')->findBy(["name"=>$group->getLabel()]);
                foreach($pages as $page) {
                    $page->setName($newname);
                    $this->em->persist($page);
                    $this->em->flush();                  
                }
                // Renommer calendrier
                $calendars = $this->em->getRepository('CadolesPortalBundle:Calendar')->findBy(["name"=>$group->getLabel()]);
                foreach($calendars as $calendar) {
                    $calendar->setName($newname);
                    $this->em->persist($calendar);
                    $this->em->flush();                  
                }

                // Renommer blog
                $blogs = $this->em->getRepository('CadolesPortalBundle:Blog')->findBy(["name"=>$group->getLabel()]);
                foreach($blogs as $blog) {
                    $blog->setName($newname);
                    $this->em->persist($blog);
                    $this->em->flush();                  
                }

                // Renommer projet
                $projects = $this->em->getRepository('CadolesPortalBundle:Project')->findBy(["name"=>$group->getLabel()]);
                foreach($projects as $project) {
                    $project->setName($newname);
                    $this->em->persist($project);
                    $this->em->flush();                  
                }

                $group->setLabel($newname);
                $this->em->persist($group);
                $this->em->flush();                  
            }
        }
    }

    private function rolegroup(){
        
        $usergroups = $this->em->getRepository('CadolesCoreBundle:UserGroup')->findAll();
        foreach($usergroups as $usergroup) {
            if(!$usergroup->getRolegroup()) {
                $role=0;
                if($usergroup->getFgmanager()) {
                    $role=50;
                    if($usergroup->getUser()==$usergroup->getGroup()->getOwner()) $role=100;
                }

                $usergroup->setRolegroup($role);
                $this->em->persist($usergroup);
                $this->em->flush();                  
            }
        }
    }

    private function userdefaultmissing(){
        $users = $this->em->getRepository('CadolesCoreBundle:User')->findAll();
        foreach($users as $user) {
            if($user->getVisible()=="") {
                $user->setVisible(true);
                $this->em->persist($user);
                $this->em->flush();               
            }

            if($user->getAuthlevel()=="") {
                $user->setAuthlevel("simple");
                $this->em->persist($user);
                $this->em->flush(); 
            }

            if($user->getBelongingpopulation()=="") {
                $user->setBelongingpopulation("agent");
                $this->em->persist($user);
                $this->em->flush(); 
            }
        } 
    }

    private function updateorthographe01(){
        $config=$this->em->getRepository('CadolesCoreBundle:Config')->find("fgforceconnect");
        if($config) {
            $config->setHelp("Forcer la connexion afin de rendre votre site privé");
            $this->em->persist($config);
            $this->em->flush();                
        }

        $config=$this->em->getRepository('CadolesCoreBundle:Config')->find("fontfacebody");
        if($config) {
            $config->setHelp("Police générale de votre site");
            $this->em->persist($config);
            $this->em->flush();                
        }        

        $config=$this->em->getRepository('CadolesCoreBundle:Config')->find("permgroup");
        if($config) {
            $config->setHelp("Détermine quel rôle aura la permission de créer des groupes de travail");
            $this->em->persist($config);
            $this->em->flush();                
        }         

        $config=$this->em->getRepository('CadolesCoreBundle:Config')->find("permannu");
        if($config) {
            $config->setHelp("Détermine quel rôle aura la permission de voir l'annuaire");
            $this->em->persist($config);
            $this->em->flush();                
        }        

        $config=$this->em->getRepository('CadolesCoreBundle:Config')->find("labelbookmarkuser");
        if($config) {
            $config->setHelp("Titre de la section des items créés par l'utilisateur, et qui ne sont listés que dans cette section.");
            $this->em->persist($config);
            $this->em->flush();                
        }        

        $config=$this->em->getRepository('CadolesCoreBundle:Config')->find("labelbookmarkitem");
        if($config) {
            $config->setHelp("Titre sur la section des items créés par l'administrateur ou le modérateur, mis à la disposition de l'utilisateur, et sélectionnés par ce dernier pour apparaitre dans cette section plutôt que dans leur catégorie d'origine.");
            $this->em->persist($config);
            $this->em->flush();                
        }        
    }

    private function updateorthographe02(){
        $entityItem = $this->em->getRepository('CadolesPortalBundle:Item')->find(-398);
        if($entityItem) {
            if($entityItem->getSubtitle()!="Messagerie") {
                $entityItem->setSubtitle("Messagerie");
                $entityItem->setContent("Messagerie permettant la communication sécurisée par méls. La messagerie n’a pas pour but d’envoyer des gros fichiers mais plutôt de communiquer des informations, des liens.");
                $this->em->persist($entityItem);
                $this->em->flush();                
            }                
        }
    }

    private function purgepageprofil() {
        $page=$this->em->getRepository('CadolesPortalBundle:Page')->findOneBy(['name'=>'PROFIL - Enseignants']);
        if($page) {
            $this->em->remove($page);
            $this->em->flush();
        }

        $page=$this->em->getRepository('CadolesPortalBundle:Page')->findOneBy(['name'=>'PROFIL - Administratifs']);
        if($page) {
            $this->em->remove($page);
            $this->em->flush();
        }
    }





    private function writelnred($string) { 
        $this->output->writeln('<fg=red>'.$string.'</>');
        $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
    }
    private function writeln($string) { 
        $this->output->writeln($string);
        $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
    }   

    protected function getHeight($image) {
        $size = getimagesize($image);
        $height = $size[1];
        return $height;
    }

    // Cacul de la largeur
    protected function getWidth($image) {
        $size = getimagesize($image);
        $width = $size[0];
        return $width;
    }

    protected function resizeImage($image,$width,$height,$scale) {
        list($imagewidth, $imageheight, $imageType) = getimagesize($image);
        $imageType = image_type_to_mime_type($imageType);
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        switch($imageType) {
            case "image/gif":
                $source=imagecreatefromgif($image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                $source=imagecreatefromjpeg($image);
                break;
            case "image/png":
            case "image/x-png":
                $source=imagecreatefrompng($image);
                break;
        }

        $newImage = imagecreatetruecolor( $newImageWidth, $newImageHeight );
        imagealphablending( $newImage, false );
        imagesavealpha( $newImage, true );
        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);

        switch($imageType) {
            case "image/gif":
                imagegif($newImage,$image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                imagejpeg($newImage,$image,90);
                break;
            case "image/png":
            case "image/x-png":
                imagepng($newImage,$image);
                break;
        }

        chmod($image, 0640);
        return $image;
    }

    private function addWidget($id,$entityPage,$widgetid,$loc,$order,$title,$border,$fields) {
        $entityPagewidget = $this->em->getRepository('CadolesPortalBundle:Pagewidget')->find($id);    
        if(!$entityPagewidget) {
            $entityWidget = $this->em->getRepository('CadolesPortalBundle:Widget')->find($widgetid); 

            if($entityWidget) {
                $entityPagewidget = new Pagewidget();
                $entityPagewidget->setId($id);
                $entityPagewidget->setLoc($loc);
                $entityPagewidget->setRoworder($order);
                $entityPagewidget->setName($title);
                $entityPagewidget->setHeight($entityWidget->getHeight());
                $entityPagewidget->setAutoajust($entityWidget->getAutoajust());
                $entityPagewidget->setBorder($border);
                $entityPagewidget->setOpened($entityWidget->getOpened());
                $entityPagewidget->setIcon($entityWidget->getIcon());
                $entityPagewidget->setPage($entityPage);
                $entityPagewidget->setWidget($entityWidget);
                $entityPagewidget->setParameter($fields);
                $this->em->persist($entityPagewidget);
                $this->em->flush();
            }
        }
    }
    
    private function addWidget2Page($entityPage,$widgetid,$loc,$order,$title,$border,$fields) {
        $entityWidget = $this->em->getRepository('CadolesPortalBundle:Widget')->find($widgetid); 
        if($entityWidget) {
            $entityPagewidget = $this->em->getRepository('CadolesPortalBundle:Pagewidget')->findOneBy(["page"=>$entityPage,"widget"=>$entityWidget]);
            if(!$entityPagewidget) {
                $entityPagewidget = new Pagewidget();
                $entityPagewidget->setLoc($loc);
                $entityPagewidget->setRoworder($order);
                $entityPagewidget->setName($title);
                $entityPagewidget->setHeight($entityWidget->getHeight());
                $entityPagewidget->setAutoajust($entityWidget->getAutoajust());
                $entityPagewidget->setBorder($border);
                $entityPagewidget->setOpened($entityWidget->getOpened());
                $entityPagewidget->setIcon($entityWidget->getIcon());
                $entityPagewidget->setPage($entityPage);
                $entityPagewidget->setWidget($entityWidget);
                $entityPagewidget->setParameter($fields);
                $this->em->persist($entityPagewidget);
                $this->em->flush();
            }
        }    
    }

    private function setfgpreference() {
        $pages=$this->em->getRepository('CadolesPortalBundle:Page')->findAll();
        foreach($pages as $page) {
            $page->setFgpreference(true);
            $this->em->persist($page);
            $this->em->flush();     
        }  
    }    

    private function renamesidebar($route,$name) {
        $sidebar=$this->em->getRepository('CadolesCoreBundle:Sidebar')->findOneBy(["path"=>$route]);
        if($sidebar) {
            $sidebar->setLabel($name);
            $this->em->persist($sidebar);
            $this->em->flush();     
        }  
    }    

}
