import { type Logger } from "@foxxmd/logging";
import { CALCULATED_PLAYER_STATUSES } from "../../common/infrastructure/Atomic.ts";
import { type PlayPlatformId } from '../../../core/Atomic.ts';
import { AbstractPlayerState, type PlayerStateOptions } from "./AbstractPlayerState.ts";
import { type PlayProgress } from "../../../core/Atomic.ts";
import { type ListenProgress, ListenProgressTS } from "./ListenProgress.ts";
import { ListenRange, ListenRangeTS } from "./ListenRange.ts";
import { type Dayjs } from "dayjs";

export class GenericPlayerState extends AbstractPlayerState {
    protected newListenProgress(data?: Partial<PlayProgress>): ListenProgress {
        return new ListenProgressTS(data);
    }

    protected newListenRange(start?: ListenProgress, end?: ListenProgress, options?: object): ListenRange {
        return new ListenRangeTS(start, end);
    }

    constructor(logger: Logger, platformId: PlayPlatformId, opts?: PlayerStateOptions) {
        super(logger, platformId, opts);
    }
    
    protected currentListenSessionContinue(position?: number, timestamp?: Dayjs) {
        if (this.currentListenRange === undefined) {
            this.logger.debug('Started new Player listen range.');
            this.currentListenRange = this.newListenRange(this.newListenProgress({position, timestamp}));
        } else {
            this.calculatedStatus = CALCULATED_PLAYER_STATUSES.playing;
            this.currentListenRange.setRangeEnd(this.newListenProgress({position, timestamp}));
        }
    }

    protected currentListenSessionEnd() {
        if (this.currentListenRange !== undefined && this.currentListenRange.getDuration() !== 0) {
            this.logger.debug('Ended current Player listen range.')
            this.currentListenRange.finalize();
            this.listenRanges.push(this.currentListenRange);
        }
        this.currentListenRange = undefined;
    }
}
