<?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\Statistic;

use function GuzzleHttp\json_encode;

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

    protected function configure()
    {
        $this
            ->setName('Core:Statistic')
            ->setDescription('Calculate Statistic')
            ->setHelp('This command Calculate Statistic')
            ->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:Statistic');        
        $this->writelnred('==========================================================================================================');

        $now=new \DateTime('now');
        $yesterday=clone $now;
        $yesterday->sub(new \DateInterval('P1D'));
        $groups=$this->em->getRepository("CadolesCoreBundle:Group")->findBy(["fgcanshare"=>true]);

        // totcptvisite
        $this->writelnred('');
        $this->writelnred('== totcptvisite');        

        $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"totcptvisite"]);
        if(!$stat) {
            $stat=new Statistic();
            $stat->setKeyvalue("totcptvisite");
            $stat->setValue([]);
        }
        $value=$stat->getValue();
        $cpt= $this->em->createQueryBuilder()
                    ->select('SUM(user.visitecpt) as cpt')
                    ->from('CadolesCoreBundle:User','user')
                    ->getQuery()->getOneOrNullResult();
        $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
        $stat->setValue($value);
        $this->em->persist($stat);
        $this->em->flush();
        
        // totcptvisitegroup
        $this->writelnred('');
        $this->writelnred('== totcptvisitegroup');        

        $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"totcptvisitegroup"]);
        if(!$stat) {
            $stat=new Statistic();
            $stat->setKeyvalue("totcptvisitegroup");
            $stat->setValue([]);
        }
        $value=$stat->getValue();
        $cpt= $this->em->createQueryBuilder()
                    ->select('SUM(usergroup.visitecpt) as cpt')
                    ->from('CadolesCoreBundle:UserGroup','usergroup')
                    ->getQuery()->getOneOrNullResult();
        $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
        $stat->setValue($value);
        $this->em->persist($stat);
        $this->em->flush();

        // totcptmessage
        $this->writelnred('');
        $this->writelnred('== totcptmessage');        

        $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"totcptmessage"]);
        if(!$stat) {
            $stat=new Statistic();
            $stat->setKeyvalue("totcptmessage");
            $stat->setValue([]);
        }
        $value=$stat->getValue();
        $cpt= $this->em->createQueryBuilder()
                    ->select('COUNT(message.id) as cpt')
                    ->from('CadolesWebsocketBundle:Message','message')
                    ->getQuery()->getOneOrNullResult();
        $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
        $stat->setValue($value);
        $this->em->persist($stat);
        $this->em->flush();

        // totcptblogarticle
        $this->writelnred('');
        $this->writelnred('== totcptblogarticle');        

        $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"totcptblogarticle"]);
        if(!$stat) {
            $stat=new Statistic();
            $stat->setKeyvalue("totcptblogarticle");
            $stat->setValue([]);
        }
        $value=$stat->getValue();
        $cpt= $this->em->createQueryBuilder()
                    ->select('COUNT(blogarticle.id) as cpt')
                    ->from('CadolesPortalBundle:Blogarticle','blogarticle')
                    ->getQuery()->getOneOrNullResult();
        $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
        $stat->setValue($value);
        $this->em->persist($stat);
        $this->em->flush();
        
        // totcptprojecttask
        $this->writelnred('');
        $this->writelnred('== totcptprojecttask');        

        $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"totcptprojecttask"]);
        if(!$stat) {
            $stat=new Statistic();
            $stat->setKeyvalue("totcptprojecttask");
            $stat->setValue([]);
        }
        $value=$stat->getValue();
        $cpt= $this->em->createQueryBuilder()
                    ->select('COUNT(projecttask.id) as cpt')
                    ->from('CadolesPortalBundle:Projecttask','projecttask')
                    ->getQuery()->getOneOrNullResult();
        $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
        $stat->setValue($value);
        $this->em->persist($stat);
        $this->em->flush();

        // groupcptvisite
        $this->writelnred('');
        $this->writelnred('== groupcptvisite');     

        foreach($groups as $group) {
            $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptvisite","group"=>$group]);
            if(!$stat) {
                $stat=new Statistic();
                $stat->setKeyvalue("groupcptvisite");
                $stat->setValue([]);
                $stat->setGroup($group);
            }
            $value=$stat->getValue();
            $cpt= $this->em->createQueryBuilder()
                        ->select(['SUM(usergroup.visitecpt) as cpt'])
                        ->from('CadolesCoreBundle:UserGroup','usergroup')
                        ->Where('usergroup.group=:group')
                        ->setParameter('group', $group)
                        ->getQuery()->getOneOrNullResult();
            $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
            $stat->setValue($value);
            $this->em->persist($stat);
            $this->em->flush();        
        }

        // groupcptmessage
        $this->writelnred('');
        $this->writelnred('== groupcptmessage');     

        foreach($groups as $group) {
            $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptmessage","group"=>$group]);
            if(!$stat) {
                $stat=new Statistic();
                $stat->setKeyvalue("groupcptmessage");
                $stat->setValue([]);
                $stat->setGroup($group);
            }
            $value=$stat->getValue();
            $cpt= $this->em->createQueryBuilder()
                        ->select('COUNT(message.id) as cpt')
                        ->from('CadolesWebsocketBundle:Message','message')
                        ->Where('message.group=:group')
                        ->setParameter('group', $group)
                        ->getQuery()->getOneOrNullResult();
            $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
            $stat->setValue($value);
            $this->em->persist($stat);
            $this->em->flush();        
        }

        // groupcptblogarticle
        $this->writelnred('');
        $this->writelnred('== groupcptblogarticle');     

        foreach($groups as $group) {
            $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptblogarticle","group"=>$group]);
            if(!$stat) {
                $stat=new Statistic();
                $stat->setKeyvalue("groupcptblogarticle");
                $stat->setValue([]);
                $stat->setGroup($group);
            }
            $value=$stat->getValue();
            $cpt= $this->em->createQueryBuilder()
                        ->select('COUNT(blogarticle.id) as cpt')
                        ->from('CadolesPortalBundle:Blogarticle','blogarticle')
                        ->from('CadolesPortalBundle:Blog','blog')
                        ->Where('blogarticle.blog=blog')
                        ->andwhere(":group MEMBER OF blog.groups")
                        ->setParameter('group', $group)
                        ->getQuery()->getOneOrNullResult();
            $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
            $stat->setValue($value);
            $this->em->persist($stat);
            $this->em->flush();        
        }

        // groupcptprojecttask
        $this->writelnred('');
        $this->writelnred('== groupcptprojecttask');     

        foreach($groups as $group) {
            $stat=$this->em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptprojecttask","group"=>$group]);
            if(!$stat) {
                $stat=new Statistic();
                $stat->setKeyvalue("groupcptprojecttask");
                $stat->setValue([]);
                $stat->setGroup($group);
            }
            $value=$stat->getValue();
            $cpt= $this->em->createQueryBuilder()
                        ->select('COUNT(projecttask.id) as cpt')
                        ->from('CadolesPortalBundle:Projecttask','projecttask')
                        ->from('CadolesPortalBundle:Project','project')
                        ->Where('projecttask.project=project')
                        ->andwhere(":group MEMBER OF project.groups")
                        ->setParameter('group', $group)
                        ->getQuery()->getOneOrNullResult();
            $value[$now->format("Y-m-d")]=($cpt["cpt"]?$cpt["cpt"]:0);
            $stat->setValue($value);
            $this->em->persist($stat);
            $this->em->flush();        
        }

        $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");
    }     
}
