<?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\HttpFoundation\File\File;
use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraints\DateTime;

use Cadoles\CoreBundle\Entity\Registration;

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

    protected function configure()
    {
        $this
            ->setName('Core:PurgeFile')
            ->setDescription('Purge Files')
            ->setHelp('This command Purge the obsolete Files')
            ->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job') 
            ->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
            ->addArgument('byexec', InputArgument::OPTIONAL, 'By Cron:Exec')
        ;
    }

    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/";
        $alias              = $this->container->getParameter('alias');

        // Le script est-il executé via Cron:Exec
        $this->byexec = $input->getArgument('byexec');
        if($this->byexec=="") $this->byexec=false;

        $this->writelnred('');
        $this->writelnred('== Core:PurgeFile');        
        $this->writelnred('==========================================================================================================');

        $now=new \DateTime('now');

        // /uploads/file
        $this->writelnred('');
        $this->writelnred('== Directory = File');        

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

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->depth('== 0')->in($directory)->directories();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                $type   = explode("-",$name)[0];
                $id     = explode("-",$name)[1];

                switch($type) {
                    case "widget":
                        $entity=$this->em->getRepository("CadolesPortalBundle:Pagewidget")->find($id);
                        if(!$entity) {
                            $this->writeln($name);
                            $url=$directory."/".$name;
                            if($fs->exists($url)) {
                                $fs->remove($url);
                            }                            
                        }
                    break;

                    case "projecttask":
                        $entity=$this->em->getRepository("CadolesPortalBundle:Projecttask")->find($id);
                        if(!$entity) {
                            $this->writeln($name);
                            $url=$directory."/".$name;
                            if($fs->exists($url)) {
                                $fs->remove($url);
                            }                            
                        }
                    break;

                    case "calendarevent":
                        $entity=$this->em->getRepository("CadolesPortalBundle:Calendarevent")->find($id);
                        if(!$entity) {
                            $this->writeln($name);
                            $url=$directory."/".$name;
                            if($fs->exists($url)) {
                                $fs->remove($url);
                            }                            
                        }
                    break;
                }
            }
        }

        // /web/uploads/avatar
        $this->writelnred('');
        $this->writelnred('== Directory = Avatar');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/avatar";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                if($name!="admin.jpg"&&$name!="noavatar.png"&&$name!="system.jpg") {
                    $entity=$this->em->getRepository("CadolesCoreBundle:User")->findBy(["avatar"=>$name]);
                    if(!$entity) { 
                        $this->writeln($name);
                        $url=$directory."/".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        }                          
                    }
                }
            }
        }

        $fs = new Filesystem();
        $users=$this->em->getRepository("CadolesCoreBundle:User")->findAll();
        foreach($users as $user) {
            if(!$fs->exists($directory."/".$user->getAvatar())) {
                $this->writeln($user->getUsername());
                $user->setAvatar("noavatar.png");
                $this->em->persist($user);
                $this->em->flush();                
            }
        }

        // /web/uploads/header
        $this->writelnred('');
        $this->writelnred('== Directory = Header');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/header";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                if($name!="header.png") {
                    $entity=$this->em->getRepository("CadolesCoreBundle:Config")->findBy(["id"=>"header","value"=>"uploads/header/".$name]);
                    if(!$entity) {
                        $this->writeln($name);
                        $url=$directory."/".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        }                          
                    }
                }
            }
        }

        // /web/uploads/logo
        $this->writelnred('');
        $this->writelnred('== Directory = Logo');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/logo";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                if($name!="logo.png") {
                    $entity=$this->em->getRepository("CadolesCoreBundle:Config")->findBy(["id"=>"logo","value"=>"uploads/logo/".$name]);
                    if(!$entity) {
                        $this->writeln($name);
                        $url=$directory."/".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        }                          
                    }
                }
            }
        }

        // /web/uploads/niveau01
        $this->writelnred('');
        $this->writelnred('== Directory = Niveau01');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/niveau01";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                if($name!="logo.png") {
                    $logo=$this->em->getRepository("CadolesCoreBundle:Niveau01")->findBy(["logo"=>"uploads/niveau01/".$name]);
                    $header=$this->em->getRepository("CadolesCoreBundle:Niveau01")->findBy(["header"=>"uploads/niveau01/".$name]);
                    if(!$logo&&!$header) {
                        $this->writeln($name);
                        $url=$directory."/".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        }                          
                    }
                }
            }
        }

        // /web/uploads/slide
        $this->writelnred('');
        $this->writelnred('== Directory = Slide');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/slide";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                $entity=$this->em->getRepository("CadolesPortalBundle:Slide")->findBy(["image"=>"uploads/slide/".$name]);
                if(!$entity) {
                    $this->writeln($name);
                    $url=$directory."/".$name;
                    if($fs->exists($url)) {
                        $fs->remove($url);
                    }                          
                }
            }
        }

        // /web/uploads/icon
        $this->writelnred('');
        $this->writelnred('== Directory = Icon');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/icon";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                if(!stripos($name,"icon_")) {
                    $entity=$this->em->getRepository("CadolesPortalBundle:Icon")->findBy(["label"=>"uploads/icon/".$name]);
                    if(!$entity) {
                        $this->writeln($name);
                        $url=$directory."/".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        }                          
                    }
                }
            }
        }

        $directory=$this->container->get('kernel')->getRootDir()."/../web";
        $icons=$this->em->getRepository("CadolesPortalBundle:Icon")->findAll();
        foreach($icons as $icon) {
            if(!$fs->exists($directory."/".$icon->getLabel())) {
                $this->writeln($directory."/".$icon->getLabel());
                $this->em->remove($icon);
                $this->em->flush();
            }
        }

        // /web/uploads/blogarticle
        $this->writelnred('');
        $this->writelnred('== Directory = Blog Article');

        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/blogarticle";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                if(strpos($name,"thumb-")===false) {
                    $entity=$this->em->getRepository("CadolesPortalBundle:Blogarticle")->findBy(["image"=>"uploads/blogarticle/".$name]);
                    if(!$entity) {
                        $this->writeln($name);
                        
                        // Suppression du fichier
                        $url=$directory."/".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        } 
                        
                        // Suppression du thumb fichier
                        $url=$directory."/thumb-".$name;
                        if($fs->exists($url)) {
                            $fs->remove($url);
                        } 
                    }
                }
            }
        }

        // /web/uploads/ckeditor
        $this->writelnred('');
        $this->writelnred('== Directory = Ckeditor');
        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/ckeditor";
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->in($directory)->files();

            foreach (iterator_to_array($finder) as $file) {
                $name   = $file->getRelativePathname();
                $tofind = "/".$alias."/uploads/ckeditor/".$name;
                $find=false;
                
                // On recherche l'image dans les pages
                $result = $this->em
                        ->getRepository("CadolesPortalBundle:Page")->createQueryBuilder('page')
                        ->where('page.html LIKE :tofind')
                        ->setParameter('tofind', '%'.$tofind.'%')
                        ->getQuery()->getResult();                
                if($result) $find=true;

                // Si pas trouvé on la cherche dans les widgets
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Pagewidget")->createQueryBuilder('pagewidget')
                            ->where('pagewidget.parameter LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on la cherche dans les blogarticle
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Blogarticle")->createQueryBuilder('blogarticle')
                            ->where('blogarticle.description LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on la cherche dans les blogcomment
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Blogcomment")->createQueryBuilder('blogcomment')
                            ->where('blogcomment.description LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on la cherche dans les projecttask
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Projecttask")->createQueryBuilder('projecttask')
                            ->where('projecttask.description LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on la cherche dans les projectcomment
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Projectcomment")->createQueryBuilder('projectcomment')
                            ->where('projectcomment.description LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on la cherche dans les blogcomment
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Blogcomment")->createQueryBuilder('blogcomment')
                            ->where('blogcomment.description LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on la cherche dans les alert
                if(!$find) {
                    $result = $this->em
                            ->getRepository("CadolesPortalBundle:Alert")->createQueryBuilder('alert')
                            ->where('alert.content LIKE :tofind')
                            ->setParameter('tofind', '%'.$tofind.'%')
                            ->getQuery()->getResult();                
                    if($result) $find=true;
                }

                // Si pas trouvé on supprime
                if(!$find) {
                    $this->writeln($name);
                    $url=$directory."/".$name;
                    if($fs->exists($url)) {
                        $fs->remove($url);
                    }                       
                }
            }
        }

        // /web/uploads/ckeditor
        $this->writelnred('');
        $this->writelnred('== Directory = Flux');
        $directory=$this->container->get('kernel')->getRootDir()."/../web/uploads/flux";
        $fs = new Filesystem();
        $fs->remove($directory);
        
        
        
        $this->writeln('');
        return 1;
    }

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