import Reel from '../../systems/reels/Reel';
import { REEL_STATES } from './states';
import { State } from '@popiplay/state-machine';

/**
 * @class Deceleration
 * @extends State
 * @description Represents the deceleration phase of a reel. In this state, the reel gradually slows down
 * until it reaches the specified stop position.
 */
export default class Deceleration extends State
{
    private reel: Reel;

    /**
     * @class
     * @param {Reel} reel - The reel instance that this state belongs to.
     */
    constructor(reel: Reel)
    {
        super('Deceleration');
        this.reel = reel;
    }

    /**
     * Updates the reel's position based on its current speed and delta time.
     * The speed decreases gradually until the reel reaches its stop position.
     * @param {number} dt - Delta time since the last update, in milliseconds.
     */
    override update(dt: number): void
    {
        this.reel.position = Math.min(
            this.reel.position + (dt * 0.001 * this.reel.speed),
            this.reel.stopPosition
        );
    }

    override leave()
    {
        this.reel.onDecelerationEnded();
    }

    /**
     * Handles the transition to the stopped state once the reel reaches its stop position.
     * @param {unknown} _input - Optional input for state handling, unused in this implementation.
     */
    override handleInput(_input: unknown): void
    {
        if (this.reel.position >= this.reel.stopPosition)
        {
            this.reel.setState(REEL_STATES.BOUNCING); // Transition to the STOPPED state
        }
    }
}
