<?php

namespace App\Command;

use App\Entity\Domain;
use App\Service\DomainService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class CrmRunDomainIpCommand extends Command
{
    protected static $defaultName = 'crm:run:domains';
    private static $command = 'crm:domain:ip';
    /**
     * @var DomainService
     */
    private $domainService;

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

    protected function configure()
    {
        $this
            ->setDescription('Run Domain Ips Check');
    }

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

        $domains = $this->domainService->getAllDomains();
        $io->progressStart(count($domains));

        /** @var Domain $domain */
        foreach ($domains as $domain) {
            $command = $this->getApplication()->find(self::$command);

            $arguments = [
                'domainId' => $domain->getId(),
            ];

            $commandInput = new ArrayInput($arguments);

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

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

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