<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Command;

use CpCreation\VitiCore\Depot\Model\Depot;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

/**
 * @author Colinet Julien
 */
class DepotPositionCommand extends Command implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    private $em;

    public function __construct(EntityManagerInterface $em)
    {

        $this->em = $em;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('viti-core:depot-position');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->comment('Update Position with postal ASC …');

        $positionNull = $this->em->getRepository(Depot::class)->findOneBy(['position' => null]);
        $depots       = $this->em->getRepository(Depot::class)->findAllOrderByCountryOrderByCategoryOrderPostalAll();
        $depots1       = $this->em->getRepository(Depot::class)->findAllOrderByCountryOrderByCategoryOrderPostalAll();

        if ($positionNull)
        {
            /** @var Depot $depot */
            foreach ($depots as $key => $depot) {
                $depot->setPosition($key);
                $depot->updateTimestampsAtUpdate();
                $this->em->persist($depot);
            }

            $this->em->flush();

            /** @var Depot $depot1 */
            foreach ($depots1 as $key1 => $depot1) {
                $depot1->setPosition($key1);
                $depot1->updateTimestampsAtUpdate();
                $this->em->persist($depot1);
            }

            $this->em->flush();
        }

        return Command::SUCCESS;
    }
}
