<?php
namespace Cadoles\CoreBundle\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\HttpKernel\KernelInterface;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\ORM\EntityManager;

use Cadoles\CoreBundle\Entity\User;

global $bdd01;
global $config;

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

    protected function configure()
    {
        $this
            ->setName('Core:SetPassword')
            ->setDescription('Synchronisation Annuaire')
            ->setHelp('This command Synchro for Core')
            ->addArgument('username', InputArgument::OPTIONAL, 'username')            
            ->addArgument('password', InputArgument::OPTIONAL, 'password')
        ;
    }

    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->writelnred('');
        $this->writelnred('== Core:SetPasword');        
        $this->writelnred('==========================================================================================================');

        $username = $input->getArgument('username');
        $this->writeln($username);

        $password = $input->getArgument('password');
        $this->writeln($password);

        $user = $this->em->getRepository('CadolesCoreBundle:User')->findOneBy(array('username' => $username));
        if($user) {
            $user->setPassword($password);
            $this->em->persist($user);
            $this->em->flush();               
        }

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



}
