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

use Cadoles\CronBundle\Entity\Cron;

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

    public function __construct(ContainerInterface $container, EntityManagerInterface $em)
    {
        parent::__construct();
        $this->container = $container;
        $this->em = $em;
    }


    protected function configure()
    {
        $this
            ->setName('app:Dump')
            ->setDescription('Dump database for backup')
            ->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->output       = $output;
        $this->filesystem   = new Filesystem();
        $this->rootlog      = $this->container->get('kernel')->getProjectDir()."/var/log/";

        $this->writelnred('');
        $this->writelnred('== app:Dump');        
        $this->writelnred('==========================================================================================================');
        
        $host=$this->container->getParameter('database_host');
        $base=$this->container->getParameter('database_name');
        $username=$this->container->getParameter('database_user');
        $password=$this->container->getParameter('database_password');
   
        $cmd = sprintf('mysqldump -h %s -B %s -u %s --password=%s &>/dev/null > %s'
            , $host
            , $base
            , $username
            , $password
            , $this->rootlog."ninegate.sql"
        );

        shell_exec($cmd);

        $this->writeln('');

        return Command::SUCCESS;
    }

    protected function runCommand($command)
    {
        $command .=" >&1";
        shell_exec($command, $output, $exit_status);
        return array(
              "output"      => $output
            , "exit_status" => $exit_status
        );
    }    

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