import { groupBy } from "lodash";
import { computed, toJS } from "mobx";
import {
  model,
  Model,
  modelAction,
  ModelAutoTypeCheckingMode,
  setGlobalConfig,
  tProp,
  types,
} from "mobx-keystone";
import Ticket from "./Ticket";

setGlobalConfig({
  modelAutoTypeChecking: ModelAutoTypeCheckingMode.AlwaysOn,
});

@model("keystone/Application/Basket")
export default class Basket extends Model({
  tickets: tProp(types.array(types.model<Ticket>(Ticket)), () => []),
}) {
  get all() {
    return this.tickets;
  }

  get allToPrint() {
    const constructedArr = this.tickets.map((ticket) => {
      return ticket.returnAllJSON();
    });
    return constructedArr;
  }

  get allPlain() {
    const ticketsPlain = this.tickets.map((ticket) => {
      return ticket.allPlain;
    });
    return toJS(ticketsPlain);
  }

  get allSorted() {
    const sorted = groupBy(this.tickets, function getId(n: Ticket) {
      return n.idModel;
    });
    return Object.values(sorted);
  }

  @modelAction
  add(ticket: Ticket) {
    if (this.tickets.length <= 99) {
      this.tickets.push(ticket);
    }
  }

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

  @modelAction
  removeLast(id: string) {
    const byTemplate = this.tickets.map((el: { idModel: any }) => el.idModel);
    let index;
    if (byTemplate.includes(id)) {
      index = byTemplate.indexOf(id);
      if (index >= 0) {
        this.tickets.splice(index, 1);
      }
    }
  }

  @modelAction
  clear() {
    this.tickets.length = 0;
  }

  @computed
  get price() {
    return this.tickets.reduce(
      (sum: number, ticket: { price: number }) => sum + ticket.price,
      0
    );
  }

  @computed
  get amount() {
    return this.tickets.length;
  }
}
