// Libs
// -----------------------------------------------------------------------------
import { makeAutoObservable, runInAction } from 'mobx';

// App
// -----------------------------------------------------------------------------
import request from 'services/request';
import { environment } from 'enviroments/enviroments';

export class LicenseActivationPageStore {
  constructor() {
    makeAutoObservable(this);
  }

  isLoading = false;

  isManual = true;

  setIsManual = (value: boolean): void => {
    this.isManual = value;
  };

  token: string | undefined = undefined;

  fetchToken = async (serial: string): Promise<void> => {
    this.isLoading = true;
    try {
      const tokenResponse = await request<void, { token: string }>({
        method: 'GET',
        url: `${environment.endPoints.license.token}${serial}/`,
      });

      runInAction(() => {
        this.token = tokenResponse.data.token;
      });
    } finally {
      runInAction(() => {
        this.isLoading = false;
      });
    }
  };

  serial: string | undefined = undefined;

  setSerial = (value: string): void => {
    this.serial = value;
  };

  license: File | undefined = undefined;

  setLicense = (value: File | undefined): void => {
    this.license = value;
  };

  activateAuto = async (serial: string): Promise<void> => {
    this.isLoading = true;
    try {
      await request<void, { license: 'activated' }>({
        method: 'GET',
        url: `${environment.endPoints.license.activateAuto}${serial}/`,
      });
    } finally {
      runInAction(() => {
        this.isLoading = false;
      });
    }
  };

  activateManual = async (licenseFile: File): Promise<void> => {
    this.isLoading = true;
    try {
      const formData = new FormData();
      formData.append('file', licenseFile);
      await request<FormData, { license: 'activated' }>({
        method: 'POST',
        url: environment.endPoints.license.activateManual,
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
    } finally {
      runInAction(() => {
        this.isLoading = false;
      });
    }
  };
}
