import { action, makeObservable, observable } from 'mobx';
import { EventsJournalRecord } from '../types/default';
import { loadable } from './Decorators/LoadingDecorator';
import { Entity, EntityStore } from './EntityStore';
import { RootStore } from './RootStore';
import request from '../services/request';

type ListRecord = EventsJournalRecord;

export class EventsJournal extends Entity {
  @observable private listRecord: ListRecord;

  constructor(id: string, listRecord: any) {
    super(id);
    this.listRecord = listRecord;
  }

  get _listRecord(): any {
    return this.listRecord;
  }

  @action
  setListRecord = (value: any): void => {
    this.listRecord = value;
  };
}

export class EventsJournalStore extends EntityStore<EventsJournal> {
  @observable countEventsJournalStore: any;

  constructor(private readonly rootStore: RootStore) {
    super();
    makeObservable(this);
  }

  @loadable
  fetchEventsJournalList(page: number, pageSize: number, sorter: string): void {
    request({
      method: 'get',
      url: `events/elastic/query/aggregated-*?page=${page}&page_size=${pageSize}${sorter}`,
    }).then(
      action((response: any) => {
        this.entities.clear();
        this.total = response.data.hits.total.value;
        for (const item of response.data.hits.hits) {
          for (const event in item._source) {
            const eventsJournal = new EventsJournal(item._id, event);
            eventsJournal.setListRecord(item);
            this.entities.set(item._id, eventsJournal);
          }
        }
      }),
    );
  }

  @loadable
  queryEventsJournalList(
    page: number,
    pageSize: number,
    sorter: string,
    query: string,
  ): void {
    request({
      method: 'get',
      url: `events/elastic/query/aggregated-*?page=${page}&page_size=${pageSize}${sorter}&q=${query}`,
    }).then(
      action((response: any) => {
        this.entities.clear();
        this.total = response.data.hits.total.value;
        for (const item of response.data.hits.hits) {
          for (const event in item._source) {
            const eventsJournal = new EventsJournal(item._id, event);
            eventsJournal.setListRecord(item);
            this.entities.set(item._id, eventsJournal);
          }
        }
      }),
    );
  }
}
