import { action, makeObservable, observable, runInAction, toJS } from 'mobx';
import { loadable } from './Decorators/LoadingDecorator';
import { AssetsRecord } from '../types/default';
import { Entity, EntityStore } from './EntityStore';
import { RootStore } from './RootStore';
import { TypeMessage } from 'pages/NCIRCCDashboard/types';
import request from '../services/request';
import {
  Company,
  CompanyCreateUpdate,
  LocationCodeList,
  NCIRCCNotificationUpdateIncidentAttack,
  NCIRCCNotificationUpdateVulnerability,
  NCIRCCNotifictionRetrive,
  NotificationStatusEnum,
} from '../myApi';
import { environment } from '../enviroments/enviroments';
import { TypeNCIRCCStatusButtonText } from '../pages/IncidentsDashboard/IncidentsCardInfo/types';

type ListRecord = AssetsRecord;

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

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

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

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

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

  @observable notifications = [];

  @observable comments: TypeMessage[] = [];

  @observable isCompanyInformation = false;

  @observable notification: NCIRCCNotifictionRetrive | null = null;

  // Требуется ли уведомлению дополнения?
  @observable isAdditionNotification: TypeNCIRCCStatusButtonText =
    TypeNCIRCCStatusButtonText.Send;

  // Получение всех уведомлений
  @loadable
  async fetchAllNotification(page: number, pageSize: number): Promise<void> {
    const response = await request({
      method: 'get',
      url:
        page && pageSize
          ? `ncircc/notifications/?page=${page}&pageSize=${pageSize}`
          : `ncircc/notifications/`,
    });

    runInAction(() => {
      this.total = response.data.count;
      this.notifications = response.data.results;
    });
  }

  setIsAdditionNotification = (value: TypeNCIRCCStatusButtonText): void => {
    this.isAdditionNotification = value;
  };

  // Получение всех комментариев по id уведомления
  async fetchCommentsOnId(id: number): Promise<void> {
    const response = await request({
      method: 'get',
      url: `ncircc/notifications/${id}/comments/`,
    });

    runInAction(() => {
      this.comments = response.data;
    });
  }

  resetNotificationById = (): void => {
    this.notification = null;
  };

  // Отправка комментария по id уведомления
  async postCommentsOnId(id: number, text: string): Promise<void> {
    const response = await request({
      method: 'post',
      url: `ncircc/notifications/${id}/comments/`,
      data: { text },
    });

    runInAction(() => {
      this.comments.unshift(response.data);
    });
  }

  // Получение списка решионов
  fetchLocation = async (): Promise<LocationCodeList> => {
    const response = await request({
      method: 'get',
      url: `company/locations/`,
    });
    return response.data;
  };

  // Получение информации о компании
  fetchCompanyInfo = async (): Promise<Company> => {
    const response = await request({
      method: 'get',
      url: `company/`,
    });

    this.isCompanyInformation = !!response.data?.name;

    return response.data;
  };

  // Создание компании
  postCompanyInfo = async (data: CompanyCreateUpdate): Promise<void> => {
    await request({
      method: 'post',
      url: `company/`,
      data,
    });
  };

  //Получение с бэка информации по id notification
  async getNotificationById(id: number): Promise<NCIRCCNotifictionRetrive> {
    const response = await request({
      method: 'get',
      url: `ncircc/notifications/${id}/`,
    });

    if (
      response.data.notification_status ===
      NotificationStatusEnum.TypeТребуетсяДополнение
    ) {
      this.isAdditionNotification = TypeNCIRCCStatusButtonText.Addition;
    } else {
      this.isAdditionNotification = TypeNCIRCCStatusButtonText.Show;
    }

    this.notification = toJS(response.data);

    return response.data;
  }

  // Создание уведомления
  async postNotification(
    data: NCIRCCNotifictionRetrive,
  ): Promise<NCIRCCNotifictionRetrive> {
    const response = await request({
      method: 'post',
      url: `ncircc/notifications/`,
      data,
    });

    this.notification = toJS(response.data);

    return response.data;
  }

  // Редактирование уведомления в случае если требуется дополнение
  async patchNotification(
    notificationId: number,
    data:
      | NCIRCCNotificationUpdateIncidentAttack
      | NCIRCCNotificationUpdateVulnerability,
  ): Promise<NCIRCCNotifictionRetrive> {
    const response = await request({
      method: 'patch',
      url: `ncircc/notifications/${notificationId}/`,
      data,
    });
    return response.data;
  }
}
