<?php

namespace FiloBlu\Esb\Console\Command;

use FiloBlu\Esb\Api\DispatcherInterface;
use FiloBlu\Esb\Api\DispatcherInterfaceFactory;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class Dispatch
 * @package FiloBlu\Esb\Console\Command
 */
class Dispatch extends Command
{
    /**
     * @var State
     */
    protected $state;

    /**
     * @var DispatcherInterfaceFactory
     */
    private $dispatcherFactory;

    /**
     * Dispatch constructor.
     * @param DispatcherInterfaceFactory $dispatcherFactory
     * @param State $state
     * @param string $name
     */
    public function __construct(DispatcherInterfaceFactory $dispatcherFactory, State $state, $name = null)
    {
        $this->state = $state;
        $this->dispatcherFactory = $dispatcherFactory;
        parent::__construct($name);
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|void|null
     * @throws LocalizedException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $this->state->getAreaCode();
        } catch (LocalizedException $e) {
            $this->state->setAreaCode(Area::AREA_ADMINHTML);
        }

        /** @var DispatcherInterface $dispatcher */
        $dispatcher = $this->dispatcherFactory->create();
        $dispatcher->dispatch();
        return 0;
    }

    /**
     *
     */
    protected function configure()
    {
        $this->setName('filoblu:esb:dispatch')
            ->setDescription('Dispatch esb events');
    }
}
