/* Copyright (C) 2024-2025 LibreWeddingPlanner contributors*/

import { Serializable } from "../api/abstract-api";
import { Entity } from "./definitions";
import { Group } from "./group";
import { Guest } from "./guest";

export type Discomfort = {
  discomfort: number;
  breakdown: {
    tableSizePenalty: number;
    cohesionPenalty: number;
  }
}

export type Table = {
  number: number;
  guests: Guest[];
  discomfort: Discomfort;
}

export class TableSimulation implements Entity {
  id?: string;
  tables: Table[];
  progress: number;

  constructor(id?: string, tables?: Table[], progress?: number) {
    this.id = id;
    this.tables = tables || [];
    this.progress = progress || 0;
  }
}

export class TableSimulationSerializer implements Serializable<TableSimulation> {
  fromJson(data: any): TableSimulation {
    return new TableSimulation(data.id, data.tables.map((table: any) => {
      return {
        number: table.number,
        guests: table.guests.map((guest: any) => new Guest(guest.id, guest.name, guest.color, guest.status, [], guest.group)),
        discomfort: {
          discomfort: table.discomfort.discomfort,
          breakdown: {
            tableSizePenalty: table.discomfort.breakdown.table_size_penalty,
            cohesionPenalty: table.discomfort.breakdown.cohesion_penalty,
          }
        },
      }
    }), data.progress);
  }

  toJson(simulation: TableSimulation): string {
    return JSON.stringify({ simulation: { tables: simulation.tables.map((table) => {
      return {
        number: table.number,
        guests: table.guests.map((guest) => {
          return {
            id: guest.id,
            name: guest.name,
            color: guest.color,
            status: guest.status,
            children: guest.children,
            group: new Group(guest.group?.id, guest.group?.name)
          }
        }),
        discomfort: table.discomfort,
      }
    }) } });
  }

  apiPath(): string {
    return 'tables_arrangements';
  }
}

