<?php

namespace App\Command;

use App\Entity\Advertisement;
use App\Entity\Log;
use Doctrine\ORM\UnitOfWork;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use App\Logger\DbHandler;

class RemoveExpiredAdsCommand extends ContainerAwareCommand
{
    /** @var LoggerInterface  */
    private $logger;

    /** @var OutputInterface $output */
    private $output;

    private $dbLogger;

    public function __construct(LoggerInterface $logger,DbHandler $dbLogger)
    {
        parent::__construct();
        $this->logger = $logger;
        $this->dbLogger = $dbLogger;
    }

    protected function configure()
    {
        $this
            ->setName('emotiqhome:remove_expired')
            ->setDescription(sprintf('Supprimer les annonces non soumis lors import'));
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;
        $em = $this->getContainer()->get('doctrine')->getManager();

        $now = new \DateTime();
        $timeStart = $now->format("H:i");
        $this->log(sprintf("Lancement de la commande 'emotiqhome:remove-expired' à %s",$timeStart));

        $agencyList = $em->getRepository('App\Entity\AgencyQueue')->getList(50);

        while(count($agencyList) > 0){
            foreach ($agencyList as $agency) {
                $this->log(sprintf("Agence : %s",$agency->getAgency()->getName()));
                $ads = $em->getRepository(Advertisement::class)->listNonImportedByAgency($agency->getAgency()->getId(),50);

                $count = count($ads);
                $total = $count;
                while($count>0){
                    foreach ($ads as $ad) {
                        try{
                            foreach ($ad->getFiles() as $picture) {
                                $path = 'public/uploads/pictures/' . $picture->getPath();
                                if(file_exists($path)){
                                    unlink($path);
                                }
                            }
                            $em->remove($ad);
                        }catch (\Exception $exception){
                            $this->exception(sprintf('Annonce %s ignorée : %s',$ad->getPolirisId(),$exception->getMessage()),$exception);
                        }
                    }
                    $em->flush();
                    $em->clear();

                    $ads = $em->getRepository(Advertisement::class)->listNonImportedByAgency($agency->getAgency()->getId(),50);
                    $count = count($ads);
                    $total = $total + $count;
                }
                try {
                    $stmt = $em->getConnection()->prepare("UPDATE advertisement set imported=false WHERE agency_id=:agency_id");
                    $stmt->bindValue("agency_id", $agency->getId());
                    $stmt->execute();
                    if(!$this->isEntityAttached($em,$agency)){
                        $agency = $em->merge( $agency );
                    }
                    $em->remove($agency);
                    $em->flush();
                }catch (\Exception $exception){
                    $this->exception('Agence '.$agency->getAgency()->getName().' : '.$exception->getMessage());
                }
            }
            $agencyList = $em->getRepository('App\Entity\AgencyQueue')->getList(50);
        }

        $q = $em->getConnection()->prepare('SELECT count(*) as cnt FROM emotiqhome.to_import where imported=false');
        $q->execute();
        $cntResult = $q->fetchAll();

        $settings = $em->getRepository('App\Entity\Settings')->find(1);

        if(sizeof($cntResult)>0 && $cntResult[0]['cnt']=='0'&& !is_null($settings) && $settings->getReadyToClean()){

            /*$this->log(sprintf("Traitement des autres annonces"));
            $ads = $em->getRepository(Advertisement::class)->listNonImported(50);
            $count = count($ads);
            $total = $count;
            while($count>0){
                foreach ($ads as $ad) {
                    try{
                        foreach ($ad->getFiles() as $picture) {
                            $path = 'public/uploads/pictures/' . $picture->getPath();
                            if(file_exists($path)){
                                unlink($path);
                            }
                        }
                        $em->remove($ad);
                    }catch (\Exception $exception){
                        $this->exception(sprintf('Annonce %s ignorée : %s',$ad->getPolirisId(),$exception->getMessage()),$exception);
                    }
                }
                $em->flush();
                $em->clear();

                $ads = $em->getRepository(Advertisement::class)->listNonImported(50);
                $count = count($ads);
                $total = $total + $count;
            }
            $q = $em->getConnection()->prepare('SELECT count(*) as cnt FROM emotiqhome.advertisement where imported=false and user_id=1');
            $q->execute();
            $cntAdvert = $q->fetchAll();
            if(sizeof($cntAdvert)>0 && $cntAdvert[0]['cnt']=='0' ) {
                $q = $em->getConnection()->prepare('UPDATE settings set ready_to_import=1,ready_to_clean=0 where id=1');
                $q->execute();
                $q = $em->getConnection()->prepare('UPDATE advertisement set imported=false where user_id=1');
                $q->execute();
            }*/
            $q = $em->getConnection()->prepare('UPDATE advertisement set imported=false where user_id=1');
            $q->execute();
        }

        $now = new \DateTime();
        $timeStart = $now->format("H:i");
        $output->writeln("Fin traitement a".$timeStart);
    }

    private function isEntityAttached($entityManager, $entity): bool
    {
        $unitOfWork = $entityManager->getUnitOfWork();
        $entityState = $unitOfWork->getEntityState($entity);

        return $entityState === UnitOfWork::STATE_MANAGED;
    }

    /**
     * @param string $message
     */
    private function log(string $message)
    {
        $this->output->writeln("INFO : ".$message);
    }

    /**
     * @param string $message
     */
    private function error(string $message)
    {
        $this->output->writeln("ERREUR : ".$message);
    }

    /**
     * @param string $message
     */
    private function exception(string $message)
    {
        $this->output->writeln("CRITIQUE : ".$message);
    }
}