<?php declare(strict_types=1);

namespace Newland\Toubiz\Search\Neos\Progress;

use Newland\Contracts\Neos\Search\ProgressHandler;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;

class ProgressBarHandler implements ProgressHandler
{

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

    /** @var ProgressBar */
    protected $bar;

    /** @var string */
    protected $lastTitle;

    public function __construct(OutputInterface $output)
    {
        $this->output = $output;
    }

    public function informProgress(string $title, int $current, ?int $total): void
    {
        if ($title !== $this->lastTitle) {
            $this->bar = $this->initializeBar($title);
        }
        if ($total && $total !== $this->bar->getMaxSteps()) {
            $this->bar->setMaxSteps($total);
        }

        $this->bar->setProgress($current);
    }

    private function initializeBar(string $name): ProgressBar
    {
        if ($this->bar !== null) {
            $this->bar->finish();
        }

        $this->lastTitle = $name;
        $bar = new ProgressBar($this->output);
        $bar->setFormat('%current% [%bar%] ' . $name);
        $bar->start();
        return $bar;
    }
}
