import type { ResponseUser } from "@components/repo/event";
import type { EventFight, ExtendedEvent, ResponseGroups, ResponseRelation, SWEvent } from "@components/types/event";
import type { Team } from "@components/types/team";
import { derived } from "svelte/store";

export class EventModel {
    public event: SWEvent = $state({} as SWEvent);
    public teams: Array<Team> = $state([]);
    public groups: Array<ResponseGroups> = $state([]);
    public _fights: Array<EventFight> = $state([]);
    public referees: Array<ResponseUser> = $state([]);
    public relations: Array<ResponseRelation> = $state([]);

    public fights = $derived(this.remapFights(this._fights, this.relations));

    constructor(data: ExtendedEvent) {
        this.event = data.event;
        this.relations = data.relations;
        this.teams = data.teams;
        this.groups = data.groups;
        this._fights = data.fights;
        this.referees = data.referees;
    }

    private remapFights(v: Array<EventFight>, rels: Array<ResponseRelation>) {
        return v.map((fight) => {
            let f = JSON.parse(JSON.stringify(fight)) as EventFight;

            let blueTeamRelation = "";
            let redTeamRelation = "";

            let relations = rels.filter((relation) => relation.fight === f.id);

            relations.forEach((relation) => {
                let str = "";
                if (relation.type === "FIGHT") {
                    str = `${relation.fromPlace === 0 ? "Gewinner" : "Verlierer"} von ${relation.fromFight?.blueTeam.name} vs ${relation.fromFight?.redTeam.name} (${new Date(
                        relation.fromFight?.start ?? 0
                    ).toLocaleTimeString("de-DE", {
                        timeStyle: "short",
                    })})`;
                } else {
                    str = `${relation.fromPlace + 1}. Platz von ${relation.fromGroup?.name}`;
                }

                if (relation.team === "BLUE") {
                    blueTeamRelation = str;
                } else {
                    redTeamRelation = str;
                }
            });

            return {
                ...f,
                blueTeam: {
                    ...f.blueTeam,
                    nameWithRelation: blueTeamRelation ? `${f.blueTeam.name} (${blueTeamRelation})` : f.blueTeam.name,
                },
                redTeam: {
                    ...f.redTeam,
                    nameWithRelation: redTeamRelation ? `${f.redTeam.name} (${redTeamRelation})` : f.redTeam.name,
                },
            };
        });
    }
}

export type EventFightModel = (typeof EventModel.prototype.fights)[number];
