import {arraysAreEqual} from "../utils";

export default class PathHistory {
    public currentIndex: number = $state(-1);
    public history: string[][] = $state([]);

    public canForward: boolean = $derived(this.currentIndex < this.history.length - 1);
    public canBack: boolean = $derived(this.currentIndex > 0);

    public newPath(path: string[]) {
        let current = this.getCurrent();
        if (current &&  arraysAreEqual(path, current)) {
            return;
        }

        this.currentIndex ++;
        this.history = this.history.slice(0, this.currentIndex);
        this.history.push(this.copy(path));
    }

    public goBack(): string[] | undefined {
        if (!this.canBack) return undefined;
        this.currentIndex--;
        return this.getCurrent();
    }

    public goForward(): string[] | undefined {
        if (!this.canForward) return undefined;
        this.currentIndex++;
        return this.getCurrent();
    }

    public jump(i: number): string[] | undefined {
        if (i >= 0 && i < this.history.length) {
            this.currentIndex = i;
            return this.getCurrent();
        }
        return undefined;
    }

    public getCurrent(): string[] | undefined {
        if (!this.history || this.currentIndex < 0 || this.currentIndex >= this.history.length) return undefined;
        return this.copy(this.history[this.currentIndex])
    }

    private copy(path: string[]) {
        const _path: string[] = [];

        for (let item of path) {
            _path.push(item);
        }
        return _path;
    }
}