<?php

namespace idoit\Module\JDisc\Helper;

use idoit\Module\JDisc\Helper\JDiscProgressBarInterface;
use idoit\Module\JDisc\Helper\SSEMessenger;

class JDiscWebProgressBar implements JDiscProgressBarInterface
{
    private string $message = '';
    private int $id = 0;
    private int $max = 0;
    private int $step = 0;
    private float $minSecondsBetweenRedraws = 1 / 3;
    private float $lastWriteTime = 0;

    public function __construct($id = 0)
    {
        $this->id = $id;
    }

    public function setId(int $id): void
    {
        $this->id = $id;
    }

    public function minSecondsBetweenRedraws(float $seconds): void
    {
        $this->minSecondsBetweenRedraws = $seconds;
    }

    public function setMaxSteps(int $max): void
    {
        $this->max = $max;
    }

    public function setMessage(string $message, string $name = 'message'): void
    {
        $this->message = $message;
    }

    public function advance(int $step = 1): void
    {
        $this->step += $step;

        $timeInterval = microtime(true) - $this->lastWriteTime;

        if ($timeInterval < $this->minSecondsBetweenRedraws & $this->step < $this->max) {
            return;
        }

        $this->lastWriteTime = microtime(true);

        $sse = SSEMessenger::getInstance();
        $sse->sendProgressMessage($this->id, $this->step, $this->max, $this->message);
    }

    public function finish(): void
    {
        // do nothing for now
    }
}
