<?php

namespace App\Command;

use App\Entity\Prospect;
use App\Service\ProspectService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class CrmRunProspectCommand extends Command
{
    protected static $defaultName = 'crm:run:prospect';
    protected static $command = 'crm:domain:check';
    /**
     * @var ProspectService
     */
    private $prospectService;

    public function __construct(ProspectService $prospectService, $name = null)
    {
        parent::__construct($name);
        $this->prospectService = $prospectService;
    }

    protected function configure()
    {
        $this
            ->setDescription('Run Prospect Checks');
    }

    /**
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->createProgressBar();

        //Prospect Provider
        $prospects = $this->prospectService->getNotUpdatedLastMonth();
        $io->progressStart(count($prospects));

        $command = $this->getApplication()->find(self::$command);

        /** @var Prospect $prospect */
        foreach ($prospects as $prospect) {
            if (null !== $prospect->getDomain()) {
                $commandInput = new ArrayInput(['domainId' => $prospect->getDomain()->getId()]);
                $output = new BufferedOutput();

                try {
                    $command->run($commandInput, $output);
                } catch (\Exception $e) {
                    $io->error($e->getMessage());

                    continue;
                }
            }
            $io->progressAdvance(1);
        }

        $io->progressFinish();
        $io->success('Prospects have been checked!');
    }
}
