<?php
namespace Cadoles\WebsocketBundle\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;

class CountMessageCommand extends Command
{    protected function configure()
    {
        $this
            ->setName('Websocket:CountMessage')
            ->setDescription('Count number of messages not read and send mail notification')
            ->setHelp('Count number of message')
            ->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job') 
            ->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron') 
        ;
    }

    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/";
        $this->noreply      = $this->container->getParameter('noreply');
        
        // S'assurer que la fonction de notification de mail est bien actif
        $config = $this->em->getRepository("CadolesCoreBundle:Config")->find("fgnotifgroup");        
        if($config && !$config->getValue()) return 1;


        $this->writelnred('');
        $this->writelnred('== Websocket:Countmessage');        
        $this->writelnred('==========================================================================================================');

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

        // Config
        $this->appname = $this->em->getRepository("CadolesCoreBundle:Config")->findOneBy(["id"=>"appname"])->getValue();
        $this->url= "https://".$this->container->getParameter('weburl')."/".$this->container->getParameter('alias');

        $now=new \DateTime('now');
        $now->modify("-1 day");

        // Pour chaque groupe purger l'ensemble des message > 100
        $groups=$this->em->getRepository("CadolesCoreBundle:Group")->findAll();
        foreach($groups as $group) {
            // On garde les 100 premiers
            $qb = $this->em->createQueryBuilder();
            $messagestokeep = $qb
                        ->select('m.id')
                        ->from('CadolesWebsocketBundle:Message', 'm')
                        ->where('m.group = :group')
                        ->setParameter('group', $group)
                        ->orderBy('m.id','DESC')
                        ->setMaxResults(100)
                        ->getQuery()->getArrayResult();       
            
            // Sur l'ensemble des messages
            $qb = $this->em->createQueryBuilder();
            $messages = $qb
                        ->select('m')
                        ->from('CadolesWebsocketBundle:Message', 'm')
                        ->where('m.group = :group')
                        ->setParameter('group', $group)
                        ->getQuery()->getResult();            

            foreach($messages as $message) {
                // S'il ne fait pas parties des 100 premiers on le supprime
                if(!in_array(["id"=>$message->getId()],$messagestokeep)) {
                    $this->writeln("PURGE ".$message->getId());
                    $this->em->remove($message);
                    $this->em->flush();                        
                }
            }

        }

        // Pour chaque utilisateur
        $users=$this->em->getRepository("CadolesCoreBundle:User")->findAll();
        foreach($users as $user) {
            $cptnotread=0;
            $body="";

            // Pour chaque group de l'utilisateur
            foreach($user->getGroups() as $usergroup) {
                // On calcule le nombre de message non lu pour l'utilisateur'
                $group=$usergroup->getGroup();
                if($group->getFgcanshare()) {
                    $qb = $this->em->createQueryBuilder();
                    $messages = $qb
                                ->select('m')
                                ->from('CadolesWebsocketBundle:Message', 'm')
                                ->where('m.group = :group')
                                ->andWhere('m.user != :user')
                                ->andWhere('m.submitdate >= :date')
                                ->setParameter('group', $group)
                                ->setParameter('user', $user)
                                ->setParameter('date',$now)
                                ->getQuery()->getResult();
                    foreach($messages as $message) {
                        if(!$message->getReaders() || !$message->getReaders()->contains($user)) {
                            $cptnotread++;
                            $body.="<hr><b>".$message->getGroup()->getLabel()."</b><br>".$message->getUser()->getLastname()." ".$message->getUser()->getFirstname()."<br><br>".$message->getTopic();
                        }
                    }
                }
            }

            // S'il l'utilisateur a des messages non lus
            if($cptnotread>0) {
                $this->writeln($user->getUsername()." notifié de ".$cptnotread." messages non lus");

                $template="template";

                $mail_params=array(
                    "subject" => $this->appname." : Messages non lus",
                    "body_html"=>"<p>Vous avez ".$cptnotread." messages non lus sur ".$this->appname."</p><p>Vous pouvez les consulter sur <a href='".$this->url."'>".$this->url."</a></p>".$body,
                    "body_text"=>"Vous avez ".$cptnotread." messages non lus sur ".$this->appname."\nVous pouvez les consulter sur ".$this->url.$body,
                );          

                $message = $this->container->get('cadoles.core.service.mail');
                $message->sendEmail($template, $mail_params, $user->getEmail(), $this->noreply, $this->appname);                
            } 
        }
        $this->writeln('');
        return 1;
    }


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