import produce from "immer";
import { SphereContext, SphereController } from "../../base";
import {
  Presentation,
  PresentationAgenda,
  PresentationSummaryStates,
  getPresentationSummaryInitState,
} from "./presentationSummaryState";

export interface PresentationSummaryEvents {
  // Events will be added as needed
}

export class PresentationSummaryController extends SphereController<
  PresentationSummaryStates,
  PresentationSummaryEvents
> {
  key = "presentationSummary";

  constructor(context: SphereContext) {
    super(context, getPresentationSummaryInitState());
  }

  setPPTs(ppts: Presentation[]) {
    this.setState("ppts", ppts);
    this.updateAgendaPPTMap();
  }

  setAgendas(agendas: PresentationAgenda[]) {
    this.setState("agendas", agendas);
    this.updateAgendaPPTMap();
  }

  updateAgendaPPTMap = () => {
    const agendaPPTMap: Record<string, { ppts: Presentation[] }> = {};

    const ppts = this.getState("ppts");
    const agendas = this.getState("agendas");

    if (agendas.length === 0) {
      this.setState("agendaPPTMap", agendaPPTMap);
      return;
    }

    ppts.forEach(ppt => {
      let foundAgenda: PresentationAgenda | undefined;
      agendas.some((agenda, index) => {
        if (index === 0 && agenda.beginTime > ppt.beginTime) {
          foundAgenda = agenda;
          return true;
        }

        if (ppt.beginTime > agenda.endTime) {
          const nextAgenda = agendas[index + 1];
          if (!nextAgenda || ppt.beginTime < nextAgenda.beginTime) {
            foundAgenda = agenda;
            return true;
          }
        }

        if (ppt.beginTime >= agenda.beginTime && ppt.beginTime <= agenda.endTime) {
          foundAgenda = agenda;
          return true;
        }
        return false;
      });

      if (foundAgenda) {
        if (!agendaPPTMap[foundAgenda.id]) {
          agendaPPTMap[foundAgenda.id] = {
            ppts: [],
          };
        }

        // console.log('debug foundAgenda', foundAgenda, ppt);

        agendaPPTMap[foundAgenda.id].ppts.push(ppt);
      }
    });

    this.setState("agendaPPTMap", agendaPPTMap);
  };

  removePPTById(id: string) {
    const ppts = this.getState("ppts");
    const pos = ppts.findIndex(ppt => {
      return ppt.id === id;
    });
    if (pos === -1) {
      return;
    }
    const newPPTs = produce(ppts, draft => {
      draft.splice(pos, 1);
    });

    this.setPPTs(newPPTs);
  }
}
