<?php

namespace App\Command;

use App\Message\DomainIpCheckedMessage;
use App\Service\DomainService;
use App\Tools\Domain;
use Doctrine\ORM\EntityNotFoundException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Messenger\MessageBusInterface;

class CrmDomainIpCheckCommand extends Command
{
    protected static $defaultName = 'crm:domain:ip';
    /**
     * @var MessageBusInterface
     */
    private $bus;
    /**
     * @var DomainService
     */
    private $domainService;
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(MessageBusInterface $bus, DomainService $domainService, LoggerInterface $logger,
                                ?string $name
                                = null)
    {
        parent::__construct($name);
        $this->bus = $bus;
        $this->domainService = $domainService;
        $this->logger = $logger;
    }

    protected function configure()
    {
        $this
            ->setDescription('Check Domain IP Address')
            ->addArgument('domainId', InputArgument::REQUIRED, 'Domain Id to check');
    }

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

        if ($domainId) {
            $io->note(sprintf('You passed an argument: %d', $domainId));
        }

        try {
            $domain = $this->domainService->getDomain($domainId);
        } catch (EntityNotFoundException $e) {
            $this->logger->alert($e->getMessage(), ['command' => $this->getName(), 'domainId' => $domainId]);
            exit(1);
        }

        $ip = Domain::getIp($domain->getFullUrl());
        if ($ip) {
            $this->bus->dispatch(new DomainIpCheckedMessage($domainId, $ip, new \DateTime()));

            $io->writeln(sprintf('IP address for %s is %s', $domain->getUrl(), $ip));
        } else {
            $io->error(sprintf('Couldn\'t determine IP address for %s', $domain->getUrl()));
        }
    }
}
