<?php

namespace idoit\Module\Report\Console\Command;

use idoit\Console\Command\AbstractCommand;
use idoit\Module\Report\Refresher\ReportsRefresher;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;

class ReportRefresherCommand extends AbstractCommand
{
    const NAME = 'report-refresher';

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * Get name for command
     *
     * @return string
     */
    public function getCommandName()
    {
        return self::NAME;
    }

    /**
     * Get description for command
     *
     * @return string
     */
    public function getCommandDescription()
    {
        return 'Refreshes one or all reports.';
    }

    /**
     * Retrieve Command InputDefinition
     *
     * @return InputDefinition
     */
    public function getCommandDefinition()
    {
        $definition = new InputDefinition();
        $definition->addOption(new InputOption('reportId', 'r', InputOption::VALUE_REQUIRED, 'ID of the report'));

        return $definition;
    }

    /**
     * Checks if a command can have a config file via --config
     *
     * @return bool
     */
    public function isConfigurable()
    {
        return true;
    }

    /**
     * Returns an array of command usages
     *
     * @return string[]
     */
    public function getCommandUsages()
    {
        return [];
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int|void|null
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $exitCode = Command::SUCCESS;
        $reportId = null;
        $this->output = $output;

        if ($input->getOption('reportId')) {
            $reportId = (int)$input->getOption('reportId');
        }

        try {
            $refresher = new ReportsRefresher();
            $refresher->refresh($reportId);
            $statistics = $refresher->getStatistics();
            $amountReports = $statistics->getCountRefreshedReports();
            $totalTime = $statistics->getTotalTime();

            $this->output->writeln("<info>It took <comment>{$totalTime}</comment> seconds to refresh <comment>{$amountReports}</comment> reports.</info>");
        } catch (Throwable $e) {
            $this->output->writeln("<error>An error occured: " . $e->getMessage() . "</error>");
        }


        return $exitCode;
    }
}
