import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { getStorageModule } from "../Storage";
import { STORAGE } from "./utils/enums";
import { createUrl } from "./utils/utils";

type StorageResponse = string | null;

const localStorage: any = getStorageModule("localStorage");

export const AppLoaderBridge = (function () {
  async function getFile(type: string): Promise<string> {
    const url: string = await createUrl(type);

    try {
      const currentEtag = await localStorage.getItem(
        `${type}Etag`,
        STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
      );

      const config: AxiosRequestConfig = {
        method: "get",
        url,
        headers: {
          "If-None-Match": currentEtag,
        },
        validateStatus: (status: number): boolean =>
          status === 200 || status === 304,
      };

      const response: AxiosResponse = await axios(config);

      const {
        data,
        headers: { etag },
        status,
      } = response;

      if (status === 304) {
        const res = await localStorage.getItem(
          type,
          STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
        );

        return JSON.stringify(res);
      }

      await localStorage.setItem(
        `${type}Etag`,
        etag,
        STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
      );

      await localStorage.setItem(
        type,
        JSON.stringify(data),
        STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
      );

      return JSON.stringify(data);
    } catch (error) {
      throw new Error("cannot retrieve configuration data for " + type);
    }
  }

  async function switchLayout(layoutID: string): Promise<boolean> {
    return await localStorage.setItem(
      STORAGE.CURRENT_LAYOUT_ID,
      layoutID,
      STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
    );
  }

  async function getCurrentLayoutId(): Promise<StorageResponse> {
    return await localStorage.getItem(
      STORAGE.CURRENT_LAYOUT_ID,
      STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
    );
  }

  async function getDefaultLayoutId(): Promise<StorageResponse> {
    return await localStorage.getItem(
      STORAGE.DEFAULT_LAYOUT_ID,
      STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
    );
  }

  return {
    getFile,
    switchLayout,
    getCurrentLayoutId,
    getDefaultLayoutId,
  };
})();
