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

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

@model("keystone/Logs/Logs")
export default class Logs extends Model({
  logs: tProp(types.array(types.model<Log>(Log)), () => []),
  faults: tProp(types.array(types.model<Fault>(Fault)), () => []),
}) {
  @modelAction
  addLog(log: Log) {
    this.logs.push(log);
  }

  @modelAction
  addFault(fault: Fault) {
    this.faults.push(fault);
  }

  @modelAction
  removeLog(log: any) {
    const index = this.logs.indexOf(log);
    if (index >= 0) {
      this.logs.splice(index, 1);
    }
  }

  @modelAction
  removeFault(fault: any) {
    const index = this.faults.indexOf(fault);
    if (index >= 0) {
      this.faults.splice(index, 1);
    }
  }

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

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

  get allLogsKeystone() {
    return this.logs;
  }

  get allFaultsKeystone() {
    return this.faults;
  }

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

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