<?php

namespace App\Command;

use App\Entity\Link;
use App\Service\LinkService;
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 CrmRunLinkIpsCommand extends Command
{
    protected static $defaultName = 'crm:run:ips';
    private static $command = 'crm:link:ip';
    /**
     * @var LinkService
     */
    private $linkService;

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

    protected function configure()
    {
        $this
            ->setDescription('Run Link IPs');
    }

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

        $links = $this->linkService->getAll();
        $io->progressStart(count($links));

        /** @var Link $link */
        foreach ($links as $link) {
            $command = $this->getApplication()->find(self::$command);

            $arguments = [
                'linkId' => $link->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('Links Ips have been checked!');
    }
}
