import { readonly, writable } from "svelte/store";

class FightConnection {
    constructor(
        public readonly fromElement: HTMLElement,
        public readonly toElement: HTMLElement,
        public readonly color: string = "white",
        public readonly background: boolean,
        public readonly offset: number = 0
    ) {}
}

export class FightConnector {
    private connections: FightConnection[] = $state([]);

    get allConnections(): FightConnection[] {
        return this.connections;
    }

    get showedConnections(): FightConnection[] {
        const showBackground = this.connections.some((conn) => !conn.background);
        return showBackground ? this.connections.filter((conn) => !conn.background) : this.connections;
    }

    addTeamConnection(teamId: number): void {
        const teamElements = document.getElementsByClassName(`team-${teamId}`);
        const teamArray = Array.from(teamElements);
        teamArray.sort((a, b) => {
            const rectA = a.getBoundingClientRect();
            const rectB = b.getBoundingClientRect();
            return rectA.top - rectB.top || rectA.left - rectB.left;
        });
        for (let i = 1; i < teamElements.length; i++) {
            const fromElement = teamElements[i - 1] as HTMLElement;
            const toElement = teamElements[i] as HTMLElement;
            this.connections.push(new FightConnection(fromElement, toElement, "white", false));
        }
    }

    addConnection(fromElement: HTMLElement, toElement: HTMLElement, color: string = "white", offset: number = 0): void {
        this.connections.push(new FightConnection(fromElement, toElement, color, true, offset));
    }

    clearConnections(): void {
        this.connections = this.connections.filter((conn) => conn.background);
    }

    clearAllConnections(): void {
        this.connections = [];
    }
}

const fightConnectorInternal = writable(new FightConnector());

export const fightConnector = readonly(fightConnectorInternal);
