// #region Imports
import { Timer } from '../../Dom/Timer';
import { ControllerBase } from './Abstracts/ControllerBase';
/**
 * Represents the `PausableTimeoutController` class.
 *
 * @public
 */
export class PausableTimeoutController extends ControllerBase {
    // #region Fields
    _config;
    _timer;
    _isRunning;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `PausableTimeoutController` class.
     *
     * @public
     */
    constructor(host, config) {
        super(host);
        this._config = config;
        this._timer = Timer.empty(() => this.handleElapsed());
        this._isRunning = false;
    }
    // #endregion
    // #region Properties
    /**
     * Gets a value indicating whether the timeout is currently running.
     *
     * @public
     * @readonly
     */
    get isRunning() {
        return this._isRunning;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    hostDisconnected() {
        super.hostDisconnected();
        this.stop();
    }
    /**
     * Starts or restarts the timeout.
     *
     * @public
     */
    start() {
        if (!this.isEnabled()) {
            return;
        }
        this._timer.setDuration(this.getDuration());
        this._timer.restart();
        this._isRunning = true;
    }
    /**
     * Stops the timeout.
     *
     * @public
     */
    stop() {
        this._timer.destroy();
        this._isRunning = false;
    }
    /**
     * Pauses the timeout.
     *
     * @public
     */
    pause() {
        if (!this._isRunning) {
            return;
        }
        this._timer.pause();
    }
    /**
     * Resumes the timeout.
     *
     * @public
     */
    resume() {
        if (!this._isRunning || !this.isEnabled()) {
            return;
        }
        this._timer.resume();
    }
    /**
     * Updates the timeout duration.
     *
     * @public
     */
    setDuration(duration) {
        this._timer.setDuration(duration);
    }
    /**
     * @private
     */
    handleElapsed() {
        this._isRunning = false;
        if (!this.isEnabled()) {
            return;
        }
        this._config.onElapsed();
    }
    /**
     * @private
     */
    isEnabled() {
        return this._config.isEnabled() && this.getDuration() > 0;
    }
    /**
     * @private
     */
    getDuration() {
        const duration = this._config.getDuration();
        if (!Number.isFinite(duration)) {
            return 0;
        }
        return Math.max(0, duration);
    }
}
/**
 * Adds a pausable timeout controller to the given host.
 *
 * @public
 * @param host The host element.
 * @param config The configuration options.
 * @returns The pausable timeout controller instance.
 */
export function addPausableTimeoutController(host, config) {
    return new PausableTimeoutController(host, config);
}
//# sourceMappingURL=PausableTimeoutController.js.map