import {
  model,
  Model,
  modelAction,
  ModelAutoTypeCheckingMode,
  setGlobalConfig,
  tProp,
  types,
} from "mobx-keystone";
import ScannedTicket from "./ScannedTicket";
import ScannedTicketSimple from "./ScannedTicketSimple";

setGlobalConfig({
  modelAutoTypeChecking: ModelAutoTypeCheckingMode.AlwaysOn,
});
@model("keystone/Application/ScannedTicketList")
export default class ScannedTicketList extends Model({
  scannedTickets: tProp(
    types.array(types.model<ScannedTicket>(ScannedTicket)),
    () => []
  ),
  scannedTicketsSimple: tProp(
    types.array(types.model<ScannedTicketSimple>(ScannedTicketSimple)),
    () => []
  ),
  useSimpleTicket: tProp(types.boolean, false).withSetter(),
  prefixSimpleTicket: tProp(types.string, "M-BL").withSetter(),
  weightToSubstractCredits: tProp(types.number, 1.0),
}) {
  @modelAction
  add(ticket: ScannedTicket) {
    this.scannedTickets.push(ticket);
  }

  @modelAction
  addSimple(ticketSimple: ScannedTicketSimple) {
    // To limit array size we shift the whole array 1 space to the left
    // Thus removing the first index, making room for another entry
    if (this.scannedTicketsSimple.length >= 50) {
      this.scannedTicketsSimple.shift();
    }
    this.scannedTicketsSimple.push(ticketSimple);
  }

  @modelAction
  remove(ticket: any) {
    const index = this.scannedTickets.indexOf(ticket);
    if (index >= 0) {
      this.scannedTickets.splice(index, 1);
    }
  }

  @modelAction
  removeSimple(ticket: any) {
    const index = this.scannedTicketsSimple.indexOf(ticket);
    if (index >= 0) {
      this.scannedTicketsSimple.splice(index, 1);
    }
  }

  @modelAction
  removeByIds(arrayOfIds: any) {
    if (typeof arrayOfIds !== undefined) {
      arrayOfIds.map((id: string) => {
        return this.remove(
          this.scannedTickets.find((x: { id: string }) => x.id === id)
        );
      });
    }
  }

  @modelAction
  removeByIdsSimple(arrayOfIds: any) {
    if (typeof arrayOfIds !== undefined) {
      arrayOfIds.map((id: string) => {
        return this.remove(
          this.scannedTicketsSimple.find((x: { id: string }) => x.id === id)
        );
      });
    }
  }

  @modelAction
  ticketById(id: string) {
    return this.scannedTickets.find((x) => x.id === id);
  }

  @modelAction
  ticketByTicketId(ticketId: number) {
    return this.scannedTickets.find((x) => x.idTicket === ticketId);
  }

  @modelAction
  simpleTicketById(simpleTicketId: string) {
    return this.scannedTicketsSimple.find((x) => x.data === simpleTicketId);
  }

  get allKeystone() {
    return this.scannedTickets;
  }

  get all() {
    const all = [];
    for (let i = 0; i < this.scannedTickets.length; i += 1) {
      all.push(this.scannedTickets[i]);
    }
    return all;
  }
}
