import { gql } from "graphql-request";
import { DateUtils, StringUtils, ObjectUtils } from "@sankhyalabs/core";
import { DataFetcher } from "../DataFetcher";
export default class ParametersFetcher {
  constructor() {
    this._embeddedParams = new Map();
    this._cachedParams = new Map();
    this.templateByQuery = new Map();
    try {
      if (window["MGE_PARAMS"] != undefined) {
        const source = atob(window['MGE_PARAMS']);
        const params = source.split('__;__');
        params.forEach(param => {
          const [key, value] = param.split("__=__");
          this._embeddedParams.set(key, value);
        });
      }
    }
    catch (error) {
      console.error("Problemas ao obter parâmetros embarcados");
      console.error(error);
    }
    this.buldTemplates();
  }
  buldTemplates() {
    this.templateByQuery.set("fetchParam", gql `query($name: String!) {
            $queryAlias$: fetchResource(name: $name){
              name
              resource
            }
        }`);
  }
  async getParam(name) {
    if (this._embeddedParams.has(name)) {
      return Promise.resolve(this._embeddedParams.get(name));
    }
    if (this._cachedParams.has(name)) {
      return this._cachedParams.get(name);
    }
    const completPath = `param://application?params=${name}`;
    const param = await DataFetcher.get().callGraphQL({
      values: { name: completPath },
      query: this.templateByQuery.get("fetchParam"),
    });
    this._cachedParams.set(name, param);
    return param;
  }
  async asString(name) {
    const paramArr = await this.getParam(name);
    return this.getValue(paramArr);
  }
  async asInteger(name) {
    const paramArr = await this.getParam(name);
    return parseInt(this.getValue(paramArr));
  }
  async asFloat(name) {
    const paramArr = await this.getParam(name);
    return parseFloat(this.getValue(paramArr));
  }
  async asBoolean(name) {
    const paramArr = await this.getParam(name);
    return (this.getValue(paramArr) === "S");
  }
  async asDate(name) {
    const paramArr = await this.getParam(name);
    return DateUtils.strToDate(this.getValue(paramArr));
  }
  async getBatchParams(names) {
    const paramArr = await this.getParam(names.join(","));
    //TODO: try to typed params val?
    const response = {};
    paramArr.forEach((param) => (response[param.name] = param.resource));
    return response;
  }
  getValue(obj = {}) {
    if (Array.isArray(obj) && obj.length > 0) {
      obj = obj[0];
    }
    if (typeof obj === "string") {
      return obj;
    }
    if (StringUtils.isEmpty(obj.resource))
      return "";
    try {
      const parameter = ObjectUtils.stringToObject(obj.resource);
      const [key] = Object.keys(parameter);
      return parameter[key];
    }
    catch (error) {
      console.warn("Erro ao converter string JSON.");
    }
  }
}
