<?php

namespace App\Command\App\Fix;

use App\Service\Domain\Stat\CheckService;
use App\Service\Domain\StatService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class DomainChecksCommand extends Command
{
    protected static $defaultName = 'app:fix:domain:checks';
    /**
     * @var StatService
     */
    private $statService;
    /**
     * @var CheckService
     */
    private $checkService;

    public function __construct(StatService $statService, CheckService $checkService, $name = null)
    {
        parent::__construct($name);
        $this->statService = $statService;
        $this->checkService = $checkService;
    }

    protected function configure()
    {
        $this
            ->setDescription('Fix domain check to include diff value');
    }

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

        $stats = $this->statService->getAll();
        $io->createProgressBar();

        $io->progressStart(count($stats));

        foreach ($stats as $stat) {
            $checks = $this->checkService->getByStat($stat->getId());
            foreach ($checks as $index => $check) {
                if (0 === $index) {
                    $check->setDiff($check->getValue());
                } else {
                    $previousCheck = $checks[$index - 1];
                    $check->setDiff($check->getValue() - $previousCheck->getValue());
                }

                $this->checkService->save($check);
            }

            $io->progressAdvance(1);
        }

        $io->progressFinish();
    }
}
