<?php

namespace AppBundle\Command;

use AppBundle\Entity\OperationITDLC;
use AppBundle\Enum\OperationITDLCState;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class CloseOperationsCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('cgenial:closeOperations')
            ->setDescription('Close operations at j+1')
            //->addArgument('argument', InputArgument::OPTIONAL, 'Argument description')
            //->addOption('option', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get("doctrine.orm.entity_manager");
        $operations = $em->getRepository(OperationITDLC::class)->findAllOperationsToBeClosed();

        if (!empty($operations)) {
            $idtlcMailer = $this->getContainer()->get("AppBundle\\Mail\\ItdlcMailer");

            foreach($operations as $ope) {
                $output->writeln("--------------------------------------------------------");
                $ope->setState(OperationITDLCState::CLOSED);
                $output->writeln("[" . date('d/m/Y H:i:s') . "] operation ".$ope->getId()." closed");
                $reponseEng = $idtlcMailer->sendFormSatisfaction('engineer', $ope);
                $reponseTeacher = $idtlcMailer->sendFormSatisfaction('teacher', $ope);

                if (!empty($reponseEng[0]['code']) && $reponseEng[0]['code'] == "success") {
                    $output->writeln("[" . date('d/m/Y H:i:s') . "] Engineer " . $ope->getInge()->getEmail() . ' email sent successfuly');
                } else {
                    $output->writeln("[" . date('d/m/Y H:i:s') . "] Engineer " . $ope->getInge()->getEmail() . ' email unsuccessfully sent');
                }

                if (!empty($reponseTeacher[0]['code']) && $reponseTeacher[0]['code'] == "success") {
                    $output->writeln("[" . date('d/m/Y H:i:s') . "] Teacher " . $ope->getProf()->getEmail() . ' email sent successfuly');
                } else {
                    $output->writeln("[" . date('d/m/Y H:i:s') . "] Teacher " . $ope->getInge()->getEmail() . ' email unsuccessfully sent');
                }
                $output->writeln("--------------------------------------------------------");
                $em->persist($ope);
            }

            //$em->flush();
        } else {
            $output->writeln("[" . date('d/m/Y H:i:s') . "] " . count($operations) . ' operation(s) closed ');
        }
    }

}
