import {
  getRootStore,
  model,
  Model,
  modelAction,
  ModelAutoTypeCheckingMode,
  setGlobalConfig,
  tProp,
  types,
} from 'mobx-keystone';
import CryptoJS from 'crypto-js';
import ScannedTicket from './ScannedTicket';
import Template from './Template';

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

@model('keystone/Application/TemplateList')
export default class TemplateList extends Model({
  templates: tProp(types.array(types.model<Template>(Template)), () => []),
}) {
  @modelAction
  add(template: Template) {
    this.templates.push(template);
  }

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

  @modelAction
  getUserIndexById(id: string) {
    const elementPos = this.templates
      .map(function getId(u: Template) {
        return u.id;
      })
      .indexOf(id);
    return elementPos;
  }

  @modelAction
  getTemplateById(id: string) {
    console.log(' searching for: ', id);
    const tmp = this.templates.find((x) => x.id === id);
    console.log(' found: ', tmp);
    return this.templates.find((x) => x.id === id);
  }

  @modelAction
  removeByIds(arrayOfIds: any) {
    arrayOfIds.map((id: string) => {
      return this.remove(this.templates.find((x) => x.id === id));
    });
  }

  @modelAction
  getByTemplateId(idTemplate: string) {
    return this.templates.find((x) => x.idTemplate === idTemplate);
  }

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

  get allAndHidden() {
    return this.templates;
  }

  @modelAction
  returnTemplateForTicket(ticket: ScannedTicket) {
    let templateId = 'No template found';
    const stringArrayFromObject = `[${ticket.idTicket},0,${ticket.startType},${
      ticket.startTime
    },${ticket.endType},${ticket.endTime},${ticket.credits.toFixed(2)}]`;

    for (let i = 0; i < this.templates.length; i += 1) {
      let check = '';
      if (check === '') {
        check = CryptoJS.enc.Base64.stringify(
          CryptoJS.HmacSHA224(
            stringArrayFromObject,
            this.templates[i].idTemplate
          )
        );
        if (ticket.check === check) {
          templateId = this.templates[i].id;
        }
      }
    }

    return templateId;
  }
}
