<?php

namespace FiloBlu\Flow\Console\Command;

use Exception;
use FiloBlu\Flow\Cron\Fetch;
use InvalidArgumentException;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class FetchCommand
 * @package FiloBlu\Flow\Console\Command
 */
class FetchCommand extends BaseCommand
{
    /**
     * @var integer
     */
    const BUS_MAX = 4;
    /**
     * @var string
     */
    const BUS_ARGUMENT = 'bus';
    /**
     * @var Fetch
     */
    protected $cronModel;

    /**
     *
     */
    protected function configure()
    {
        $this->setName('flow:fetch')
            ->setDescription('Retrieve files/data from remote source')
            ->setDefinition([
                new InputArgument(
                    self::BUS_ARGUMENT,
                    InputArgument::OPTIONAL,
                    'Bus'
                ),
            ]);
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     * @throws LocalizedException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->ensureAreaCode($output);

        $bus = $input->getArgument(self::BUS_ARGUMENT);
        $busToProcess = $bus === null ? range(1, self::BUS_MAX) : [$bus];

        foreach ($busToProcess as $bus) {
            $this->fetchBus((int)$bus);
            $output->writeln("<info>Fetch executed on bus {$bus}!</info>");
        }

        return 0;
    }

    /**
     * @param $bus
     * @return Fetch
     * @throws Exception
     */
    protected function fetchBus($bus)
    {
        if ($bus > self::BUS_MAX) {
            throw new InvalidArgumentException(
                sprintf(
                    'Argument %s must be one of %s',
                    self::BUS_ARGUMENT,
                    implode(',', range(1, self::BUS_MAX))
                )
            );
        }

        if ($this->cronModel === null) {
            /** @var Fetch $cronModel */
            $this->cronModel = $this->fetchFactory->create();
        }

        $method = "executeBus{$bus}";
        return $this->cronModel->$method();
    }
}
