<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Console\Command;

use Magento\Framework\Console\CommandListInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class SyncAllCommand
 * @package FiloBlu\Refilo\Console\Command
 */
class SyncAllCommand extends Command
{
    /**
     * @var CommandListInterface[]
     */
    protected $commandList;

    /**
     * SyncAllCommand constructor.
     * @param array $commandList
     * @param string|null $name
     */
    public function __construct(
        $commandList = [],
        string $name = null
    )
    {
        parent::__construct($name);
        $this->commandList = $commandList;
    }

    /**
     * @inheritDoc
     */
    protected function configure()
    {
        $this->setName('refilo:sync:all');
        $this->setDescription('Sync all syncable');
        parent::configure();
    }

    /**
     * Execute the command
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $exitCode = 0;
        foreach ($this->commandList as $name => $command) {
            $output->writeln('Executing ' . $command->getName());
            // run() (public) goes through the full Symfony lifecycle and returns the exit
            // code; execute() is protected and bypasses initialize()/interact().
            $exitCode = max($exitCode, (int)$command->run($input, $output));
        }

        return $exitCode;
    }

}
