<?php

namespace Cadoles\CronBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
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\HttpFoundation\Response;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

use Cadoles\CronBundle\Entity\Cron;

class CronexecCommand extends ContainerAwareCommand
{
    private $container;
    private $em;
    private $output;
    private $filesystem;
    private $rootlog;

    protected function configure()
    {
        $this
            ->setName('Cron:Run')
            ->setDescription("Executer les commandes présente dans le bus des commandes à exécuter à la volet")
        ;
    }

    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/";
        echo $this->rootlog;
        // On supprime le fichier de log spécifique à ce script
        //$this->filesystem->remove($this->rootlog."exec.log");
        $this->filesystem->dumpFile($this->rootlog.'exec.log', "");
        $this->filesystem->chown($this->rootlog.'exec.log', "www-data");

        $cronexecs=$this->em->getRepository("CadolesCronBundle:Cronexec")->findAll();
        if($cronexecs) {
            $this->writelnred('');
            $this->writelnred('== Cron:Run');        
            $this->writelnred('==========================================================================================================');
        
            foreach($cronexecs as $cron) {
                // Récupération de la commande
                $command = $this->getApplication()->find($cron->getCommand());
                
                // Réccuépration des parametres
                $jsonparameter=json_decode($cron->getJsonargument(),true);

                // Parametre id du cron actuel
                $jsonparameter["cronid"]=$cron->getId();
                $jsonparameter["byexec"]=true;

                // Formater la chaine de parametre
                $parameter = new ArrayInput($jsonparameter);

                // Executer la commande
                $returnCode=false;
                try{
                    $returnCode = $command->run($parameter, $output);
                }
                catch(\Exception $e) { 
                    $this->writelnred("JOB EN ERREUR"); 
                } 
            }
        }
        
        return 1;
    }

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