import { appStore } from "@applicaster/zapp-react-native-redux/AppStore";
import { getStorageModule } from "../../Storage";
import { STORAGE, STORE_PLATFORM } from "./enums";

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

export async function createUrl(type: string): Promise<string> {
  const appData = appStore.get("appData");

  const {
    accountsAccountId,
    bundleIdentifier,
    store,
    versionName,
    rivers_configuration_id: defaultLayoutId,
    appFamilyId,
  } = appData;

  if (
    !(await localStorage.getItem(
      STORAGE.DEFAULT_LAYOUT_ID,
      STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
    ))
  ) {
    await localStorage.setItem(
      STORAGE.DEFAULT_LAYOUT_ID,
      defaultLayoutId,
      STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
    );
  }

  const currentLayoutId = await localStorage.getItem(
    STORAGE.CURRENT_LAYOUT_ID,
    STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
  );

  const remoteConfig: RemoteConfigurations = await localStorage.getItem(
    STORAGE.REMOTE_CONFIGURATIONS,
    STORAGE.APP_LOADER_BRIDGE_NAME_SPACE
  );

  const remoteConfigLayoutId = remoteConfig?.general_settings?.layout_id;

  /**
   * It is very important to note the order used in the customLayoutId property.
   * First we are attempting ot use the id set by layout plugin, it is an override of the defined layout.
   * Or use layout id from the remote configuration, remote config is loaded first and it has current layoutId from zapp.
   * Or use layout id that was built with the app, this id can be found in appData.json and is loaded into redux store.
   */
  const customLayoutId =
    currentLayoutId || remoteConfigLayoutId || defaultLayoutId;

  const baseURL = `https://assets-secure.applicaster.com/zapp/accounts/${accountsAccountId}`;
  const urlTemplate = `apps/${bundleIdentifier}/${STORE_PLATFORM[store]}/${versionName}`;

  switch (type) {
    case "remoteConfigurations":
      return `${baseURL}/${urlTemplate}/remote_configurations/remote_configurations.json`;
    case "pluginConfigurations":
      return `${baseURL}/${urlTemplate}/plugin_configurations/plugin_configurations.json`;
    case "layout":
      return `${baseURL}/${urlTemplate}/layouts/${customLayoutId}.json`;
    case "pipesEndpoints":
      return `${baseURL}/app_families/${appFamilyId}/data_source_providers/endpoints.json`;
    case "cellStyles":
      return `${baseURL}/app_families/${appFamilyId}/layouts/${customLayoutId}/cell_styles.json`;
    case "presetsMapping":
      return `${baseURL}/app_families/${appFamilyId}/layouts/${customLayoutId}/presets_mapping.json`;
    default:
      return null;
  }
}
