'use strict';

const DataFetcher = require('./DataFetcher-21f8c2dc.js');
const core = require('@sankhyalabs/core');

class ResourceFetcher {
  constructor() {
    this.templateByQuery = new Map();
    this.buldTemplates();
  }
  buldTemplates() {
    this.templateByQuery.set("fetchResource", DataFetcher.dist.gql `query($name: String!) {
                    $queryAlias$: fetchResource(name: $name){
                        resource
                    }
                  }`);
    this.templateByQuery.set("saveResource", DataFetcher.dist.gql `mutation($resource: InputResource!) {
                $queryAlias$: saveResource(resource: $resource){
                    name
                    resource                    
                }
              }`);
  }
  loadResource(name) {
    if (ResourceFetcher._loadingResource.has(name)) {
      return ResourceFetcher._loadingResource.get(name);
    }
    const promiseLoadResource = new Promise((resolve, reject) => {
      DataFetcher.DataFetcher.get()
        .callGraphQL({
        values: { name },
        query: this.templateByQuery.get("fetchResource"),
      })
        .then((result) => {
        resolve(result === null || result === void 0 ? void 0 : result.resource);
        ResourceFetcher._loadingResource.delete(name);
      })
        .catch((error) => {
        reject(error);
        ResourceFetcher._loadingResource.delete(name);
      });
    });
    ResourceFetcher._loadingResource.set(name, promiseLoadResource);
    return promiseLoadResource;
  }
  saveResource(resource, name) {
    return new Promise((resolve, reject) => {
      DataFetcher.DataFetcher.get()
        .callGraphQL({
        values: {
          resource: {
            name: name,
            resource: JSON.stringify(resource)
          }
        },
        query: this.templateByQuery.get("saveResource")
      })
        .then((resp) => {
        resolve(resp);
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
}
ResourceFetcher._loadingResource = new Map();

class FormConfigFetcher extends ResourceFetcher {
  constructor() {
    super();
    this.queryConfig = new Map();
    this.buildTemplatesConfig();
  }
  buildTemplatesConfig() {
    this.queryConfig.set("fetchUserAvailableConfigs", DataFetcher.dist.gql `query($name: String!) {
                    $queryAlias$: fetchUserAvailableConfigs(name: $name){
                        name
                        origin
                        key
                  }
                }`);
    this.queryConfig.set("fetchLegacyConfig", DataFetcher.dist.gql `query($name: String!) {
                    $queryAlias$: fetchLegacyConfig(name: $name){
                        name
                        resource
                  }
                }`);
    this.queryConfig.set("fetchDefaultConfig", DataFetcher.dist.gql `query($name: String!) {
                    $queryAlias$: fetchDefaultConfig(name: $name){
                        name
                        resource
                  }
                }`);
  }
  loadFormConfig(formName, resourceID) {
    return new Promise((accept, reject) => {
      Promise.all([
        this.loadResource(this.getPath(resourceID, formName)),
        this.loadResource(this.getPath(`FormCardState:${resourceID}`, formName, "form-card")),
        this.loadResource(this.getPath(resourceID, formName, "summary")),
        this.loadResource(this.getPath(resourceID, formName, "defaultValues"))
      ])
        .then(([configAsString, formCardState, summary, defaultValues]) => {
        let config;
        if (configAsString != undefined) {
          config = Object.assign(Object.assign({}, JSON.parse(configAsString)), { emptyConfig: false });
          const { tabs, fields } = config;
          if (tabs) {
            const allTabs = new Map(tabs.map(t => [t.label, t]));
            fields === null || fields === void 0 ? void 0 : fields.forEach(f => { var _a; return f.tab = ((_a = allTabs.get(this.getTabName(f.tab))) === null || _a === void 0 ? void 0 : _a.label) || allTabs.get(this.getTabName(f.tab)); });
          }
          config.fields = fields === null || fields === void 0 ? void 0 : fields.map((field) => {
            if ("readonly" in field) {
              const readOnly = field['readonly'] === true;
              delete field['readonly'];
              field.readOnly = readOnly;
            }
            return field;
          });
        }
        if (formCardState != undefined) {
          if (config == undefined) {
            config = { emptyConfig: true, fields: [] };
          }
          config.cardsState = new Map(JSON.parse(formCardState));
        }
        if (summary != undefined) {
          if (config == undefined) {
            config = { emptyConfig: true, fields: [] };
          }
          config.summary = new Map(Object.entries(JSON.parse(summary)));
        }
        if (defaultValues != undefined) {
          if (config == undefined) {
            config = { emptyConfig: true, fields: [] };
          }
          config.defaultVars = new Map(Object.entries(JSON.parse(defaultValues)));
        }
        accept(config);
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
  getTabName(tab) {
    if (typeof tab === 'object') { // ITabConfig type
      return tab.label;
    }
    return tab; //string type
  }
  saveCardState(cardsState, formName, resourceID) {
    const completePath = this.getPath(`FormCardState:${resourceID}`, formName, "form-card");
    return new Promise((resolve, reject) => {
      this.saveResource(Array.from(cardsState.entries()), completePath)
        .then((resp) => {
        resolve(new Map(JSON.parse(resp.resource)));
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
  saveConfig(config, formName, resourceID) {
    //Essas informações não devem ser salvas na configuração
    delete config.cardsState;
    delete config.defaultVars;
    delete config.summary;
    const completePath = this.getPath(resourceID, formName);
    return new Promise((resolve, reject) => {
      this.saveResource(config, completePath)
        .then((resp) => {
        resolve(JSON.parse(resp.resource));
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
  fetchUserAvailableConfigs(formName, resourceID) {
    const name = this.getPath(resourceID, formName);
    return new Promise((resolve, reject) => {
      DataFetcher.DataFetcher.get()
        .callGraphQL({
        values: { name },
        query: this.queryConfig.get("fetchUserAvailableConfigs"),
      })
        .then((result) => {
        resolve(result);
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
  fetchLegacyConfig(formName, resourceID) {
    const name = this.getPath(resourceID, formName);
    return new Promise((resolve, reject) => {
      DataFetcher.DataFetcher.get()
        .callGraphQL({
        values: { name },
        query: this.queryConfig.get("fetchLegacyConfig"),
      })
        .then((result) => {
        resolve(core.ObjectUtils.stringToObject((result === null || result === void 0 ? void 0 : result.resource) || ''));
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
  fetchDefaultConfig(formName, resourceID) {
    const name = this.getPath(resourceID, formName);
    return new Promise((resolve, reject) => {
      DataFetcher.DataFetcher.get()
        .callGraphQL({
        values: { name },
        query: this.queryConfig.get("fetchDefaultConfig"),
      })
        .then((result) => {
        if (!(result === null || result === void 0 ? void 0 : result.resource)) {
          resolve(null);
        }
        resolve(core.ObjectUtils.stringToObject(result === null || result === void 0 ? void 0 : result.resource));
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
  getPath(resourceID, name, authority = "form") {
    if (name) {
      return `cfg://${authority}/${resourceID}/${name}`;
    }
    return `cfg://${authority}/${resourceID}`;
  }
  async fetchLegacyConfigurableForm(configName) {
    const payload = { 'requestBody': { 'config': { 'chave': configName, 'tipo': 'T' } } };
    const response = await DataFetcher.DataFetcher.get().callServiceBroker('SystemUtilsSP.getConf', JSON.stringify(payload));
    if (core.ObjectUtils.isEmpty(response))
      return undefined;
    return this.buildLegacyConfigurableForm(response);
  }
  async fetchSimpleFormConfig(configName) {
    const payload = { 'requestBody': { 'formConfig': { 'configName': configName } } };
    const response = await DataFetcher.DataFetcher.get().callServiceBroker('FormConfig.getFormConfig', JSON.stringify(payload));
    return this.processConfig(response);
  }
  async saveSimpleFormConfig(configName, fieldList) {
    const payload = this.buildSaveSimpleFormConfigPayload(configName, fieldList);
    const response = await DataFetcher.DataFetcher.get().callServiceBroker('FormConfig.saveFormConfig', JSON.stringify(payload));
    this.processConfig(response);
  }
  processConfig(response) {
    if (core.ObjectUtils.isEmpty(response))
      return [];
    const fields = this.getResponseAsArray(response);
    return fields.map(field => field.name);
  }
  getResponseAsArray(response) {
    var _a, _b, _c;
    const rawFields = (_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.formConfig) === null || _a === void 0 ? void 0 : _a.layout) === null || _b === void 0 ? void 0 : _b.field) !== null && _c !== void 0 ? _c : [];
    return Array.isArray(rawFields) ? rawFields : [rawFields];
  }
  buildSaveSimpleFormConfigPayload(configName, fieldNameList) {
    const fieldList = fieldNameList.map(fieldName => { return { name: fieldName }; });
    return {
      formConfig: {
        configName,
        layout: {
          field: fieldList,
        },
        metadata: { field: [] },
      }
    };
  }
  async restoreFormConfig(configName) {
    const payload = { 'requestBody': { 'formConfig': { 'configName': configName } } };
    await DataFetcher.DataFetcher.get().callServiceBroker('FormConfig.restoreFormConfig', JSON.stringify(payload));
  }
  buildLegacyConfigurableForm(config) {
    var _a, _b, _c;
    const rawFields = (_c = (_b = (_a = config === null || config === void 0 ? void 0 : config.formConfig) === null || _a === void 0 ? void 0 : _a.layout) === null || _b === void 0 ? void 0 : _b.field) !== null && _c !== void 0 ? _c : [];
    return { emptyConfig: false, fields: Array.isArray(rawFields) ? rawFields : [rawFields] };
  }
  async fetchLayoutFormConfig(configName) {
    const payload = { 'requestBody': { 'config': { 'chave': configName, 'tipo': 'T' } } };
    const response = await DataFetcher.DataFetcher.get().callServiceBroker('SystemUtilsSP.getConf', JSON.stringify(payload));
    if (core.ObjectUtils.isEmpty(response))
      return undefined;
    return response.config;
  }
  async saveLayoutFormConfig(configName, config) {
    const payload = { 'requestBody': { 'config': Object.assign(Object.assign({}, config), { 'chave': configName, 'tipo': 'T' }) } };
    const response = await DataFetcher.DataFetcher.get().callServiceBroker('SystemUtilsSP.saveConf', JSON.stringify(payload));
    if (core.ObjectUtils.isEmpty(response))
      return undefined;
    return response;
  }
}
exports.UserConfigType = void 0;
(function (UserConfigType) {
  UserConfigType["USER"] = "USER";
  UserConfigType["DEFAULT"] = "DEFAULT";
  UserConfigType["SHARED"] = "SHARED";
})(exports.UserConfigType || (exports.UserConfigType = {}));

exports.FormConfigFetcher = FormConfigFetcher;
exports.ResourceFetcher = ResourceFetcher;
