<?php

namespace App\Command;

use App\Entity\Campaign\RobotsCheck;
use App\Service\Campaign\RobotsCheckService;
use App\Service\CampaignService;
use Doctrine\ORM\EntityNotFoundException;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
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;

class CrmCheckRobotsFileCommand extends Command
{
    protected static $defaultName = 'crm:check:robots';
    /**
     * @var Client
     */
    private $httpClient;
    /**
     * @var CampaignService
     */
    private $campaignService;
    /**
     * @var RobotsCheckService
     */
    private $robotsCheckService;

    public function __construct(Client $httpClient, CampaignService $campaignService, RobotsCheckService $robotsCheckService, string $name = null)
    {
        parent::__construct($name);
        $this->httpClient = $httpClient;
        $this->campaignService = $campaignService;
        $this->robotsCheckService = $robotsCheckService;
    }

    protected function configure()
    {
        $this
            ->setDescription('Check robots file existence')
            ->addArgument('campaignId', InputArgument::REQUIRED, 'Id of a campaign to check');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $campaignId = $input->getArgument('campaignId');

        try {
            $campaign = $this->campaignService->getCampaign($campaignId);
            $url = $campaign->getDomain()->getFullUrl();
        } catch (EntityNotFoundException $e) {
            $io->error('There is no Campaign for given ID');

            return 1;
        }

        $io->note(sprintf('Checking existence of robots file for : %s', $url));

        $check = new RobotsCheck();
        $check->setCampaign($campaign);

        try {
            $result = $this->httpClient->get(sprintf('%s/robots.txt', $url));
            $value = (string) $result->getBody();
            $check->setExist(true);
            $check->setValue($value);
        } catch (RequestException $e) {
            $io->error(sprintf('Request returned code: %s', $e->getCode()));
            $check->setExist(false);
        } catch (Exception $e) {
            $io->error($e->getMessage());
            $check->setExist(false);
        }

        $this->robotsCheckService->save($check);

        $io->success('Job finished');

        return 0;
    }
}
