<?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 Cadoles\CronBundle\Entity\Cron;

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

    protected function configure()
    {
        $this
            ->setName('Cron:Mail')
            ->setDescription('Send Mail')
            ->addArgument('message-limit', InputArgument::OPTIONAL, 'limit message Mail') 
            ->addArgument('env', InputArgument::OPTIONAL, 'env Mail') 
            ->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/";
        
        $mailer_host        = $this->getContainer()->getParameter('mailer_host');

        $this->writelnred('');
        $this->writelnred('== Cron:Mail');        
        $this->writelnred('==========================================================================================================');
        
        $command = $this->getApplication()->find("swiftmailer:spool:send");
        $tbparameter["--message-limit"]=100;
        $tbparameter["--env"]="prod";
        if($mailer_host=="/usr/sbin/sendmail")
            $tbparameter["--transport"]="swiftmailer.mailer.sendmail.transport";
        

        $parameter = new ArrayInput($tbparameter);
        try{
            $returnCode = $command->run($parameter, $output);
        }
        catch(\Exception $e) { 
            $this->writeln(""); 
            $this->writelnred("Impossible d'envoyer des mails"); 
            $this->writeln(""); 
            return 0;
        }
        $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");
    }  
}
