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

type ListRecord = EventsJournalRecord;

export class Antivirus 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: ListRecord): any => {
    this.listRecord = value;
  };
}

export class AntivirusResultsTableStore extends EntityStore<Antivirus> {
  constructor(private readonly rootStore: RootStore) {
    super();
    makeObservable(this);
  }

  async fetchAntivirusEvents(
    endpointId: number,
    page: number,
    pageSize: number,
    sorterField = '',
  ): Promise<void> {
    const result = await request({
      method: 'get',
      url: `/events/elastic/query/aggregated-*?page=${page}&page_size=${pageSize}${sorterField}&q='(type:endpoint_${endpointId}) AND (sign_category:Antivirus) AND NOT (sign_name: scan_start OR scan_stop )'`,
    });

    runInAction(() => {
      this.entities.clear();
      this.total = result.data.hits.total.value;
      for (const item of result.data.hits.hits) {
        for (const event in item._source) {
          const antivirus = new Antivirus(item._id, event);
          antivirus.setListRecord(item);
          this.entities.set(item._id, antivirus);
        }
      }
    });
  }

  async postClamAVDB(data: FormData): Promise<void> {
    await request({
      method: 'post',
      url: '/store/antivirus/',
      data,
    });
  }
}
