import { Component } from "../core/world";
import { action, component, variable } from "../utils/decorators";

@component
export class Cooldown extends Component<{
    remaining: number;
    duration: number;
}> {
    constructor(duration: number) {
        super({ remaining: duration, duration });
    }

    @variable('.')
    get ready(): boolean {
        return this.state.remaining <= 0;
    }

    @action
    reset(duration?: number): void {
        if (duration != null) this.state.duration = duration;
        this.state.remaining = this.state.duration;
    }

    @action
    clear(): void {
        if (this.state.remaining <= 0) return;
        this.state.remaining = 0;
        this.emit('ready');
    }

    @action
    update(dt: number): void {
        if (this.state.remaining <= 0) return;
        this.state.remaining -= dt;
        if (this.state.remaining <= 0) {
            this.state.remaining = 0;
            this.emit('ready');
        }
    }
}