// App
// -----------------------------------------------------------------------------
import {
  TypeFirewallDevice,
  TypeFirewallFieldValues,
  TypeFirewallStatus,
} from 'types/default';
import { GenericDataStore } from './GenericDataStore';
import { environment } from 'enviroments/enviroments';
import request from 'services/request';
import { ArmaIndustrialFirewall } from '../myApi';
import { action, observable, runInAction, toJS } from 'mobx';

export class FirewallStore extends GenericDataStore<TypeFirewallDevice> {
  constructor() {
    super(`${environment.devices.list}${environment.devices.firewall}`);
    this.override({
      firewall: observable,
      fetchFirewallDetailById: action,
      clearFirewallDetailById: action,
    });
  }

  getId = (entity: TypeFirewallDevice): number => entity.id;

  getName = (entity: TypeFirewallDevice): string => entity.name;

  private getStatusUrl = (id: TypeFirewallDevice['id']): string => {
    const { list, firewall, firewallStatus } = environment.devices;
    return `${list}${firewall}${id}/${firewallStatus}`;
  };

  getStatus = async (
    id: TypeFirewallDevice['id'],
  ): Promise<TypeFirewallStatus> => {
    const response = await request<void, TypeFirewallStatus>({
      url: this.getStatusUrl(id),
      method: 'GET',
    });
    return response.data;
  };

  private getRuleFieldsUrl = (id: TypeFirewallDevice['id']): string => {
    const { list, firewall, firewallRuleFields } = environment.devices;
    return `${list}${firewall}${id}/${firewallRuleFields}`;
  };

  getRuleFields = async (
    id: TypeFirewallDevice['id'],
  ): Promise<TypeFirewallFieldValues> => {
    const response = await request<void, TypeFirewallFieldValues>({
      url: this.getRuleFieldsUrl(id),
      method: 'GET',
    });
    return response.data;
  };

  firewall: ArmaIndustrialFirewall | null = null;

  get getFirewallById(): ArmaIndustrialFirewall | null {
    return toJS(this.firewall);
  }

  fetchFirewallDetailById = async (id: number): Promise<void> => {
    const response = await request({
      method: 'get',
      url: `devices/${environment.devices.firewall}${id}/`,
    });

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

  clearFirewallDetailById = (): void => {
    this.firewall = null;
  };
}
