<?php
namespace App\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\Filesystem\Filesystem;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\MailService;

class NotifMessageCommand extends Command
{    
    private $container;
    private $em;
    private $mail;
    private $output;
    
    private $filesystem;
    private $rootlog;
    private $appname;
    private $noreply;
    private $url;

    public function __construct(ContainerInterface $container, EntityManagerInterface $em, mailService $mail)
    {
        parent::__construct();
        $this->container = $container;
        $this->em = $em;
        $this->mail = $mail;
    }    
    
    protected function configure()
    {
        $this
            ->setName('app:NotifMessage')
            ->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->output       = $output;
        $this->filesystem   = new Filesystem();
        $this->rootlog      = $this->container->get('kernel')->getProjectDir()."/../var/log/";
        $this->noreply      = $this->container->getParameter('noreply');
        
        

        // S'assurer que la fonction de notification de mail est bien actif
        $config = $this->em->getRepository("App\Entity\Config")->find("fgnotifgroup");        
        if($config && !$config->getValue()) return Command::SUCCESS;


        $this->writelnred('');
        $this->writelnred('== app:Notifmessage');        
        $this->writelnred('==========================================================================================================');
        
        $now=new \DateTime('now');
        $fgdebug = false;

        // Config
        $this->appname = $this->em->getRepository("App\Entity\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("App\Entity\Group")->findAll();
        foreach($groups as $group) {
            // On garde les 100 premiers
            $qb = $this->em->createQueryBuilder();
            $messagestokeep = $qb
                        ->select('m.id')
                        ->from('App\Entity\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('App\Entity\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("App\Entity\User")->findAll();
        foreach($users as $user) {
            $cptnotread=0;
            $msg="";

            // 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('App\Entity\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++;
                            $msg.="<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");

                $subject=$this->appname." : Messages non lus";
                $body="<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>".$msg;
                $to = $user->getEmail();
                $from = $this->noreply;
                $fromName = $this->appname;
                $this->mail->sendEmail($subject, $body, $to, $from, $fromName);  
            } 
        }
        $this->writeln('');
        return Command::SUCCESS;
    }


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