import { h } from '@stencil/core';
import { Action, ApplicationContext, DataUnit } from '@sankhyalabs/core';
import { AnexoSistemaFetcher, AttachFetcher, DataUnitFetcher } from '../../lib';
import { VIEW_MODE } from '../../lib/utils/constants';
import { anexoSistemaCrudConfig, AnexoSistemaDataUnitFactory, attachCrudConfig, AttachFetcherDataUnitFactory, buildTaskBarManager, } from './structure';
import InMemoryLoader from '../../lib/dataUnit/InMemoryLoader';
import { SaveErrorsEnum } from '../../lib/http/data-fetcher/fetchers/AttachFetcher/interfaces';
const RESOURCE_ID = 'AnexoSistema';
const DATA_UNIT_NAME = 'br.com.sankhya.core.v3.anexoSistema';
const GRID_LEGACY_CONFIG_NAME = 'GrdCfgHtml5:grdcfg.dynaform.anexo';
const LINKORFILE_COLUMN_NAME = "ARQUIVOOULINK";
export class SnkAttach {
  constructor() {
    this.handleTaskbarClick = async ({ detail: taskbar }) => {
      if (["DOWNLOAD", "LINK"].includes(taskbar))
        return this.downloadAttachment(this._currentDataUnit.getSelectedRecord());
      if (this.fetcherType === "Attach" && ["SAVE"].includes(taskbar) && this._currentDataUnit.isDirty()) {
        await this._currentDataUnit.setFieldValue("REGISTER_KEY", this.registerKey);
      }
    };
    this.handleBack = () => {
      this._currentDataUnit.cancelEdition().then((cancelationConfirmed) => {
        if (cancelationConfirmed)
          this.back.emit();
      });
    };
    this.handleFinish = () => {
      if (!this._currentDataUnit.isDirty())
        return this.back.emit();
      if (!this.validateAnexoSistema()) {
        return;
      }
      this._currentDataUnit.saveData().then(() => {
        this.showFinishedToast();
        this.back.emit();
      });
    };
    this.gridLegacyConfigName = undefined;
    this.fetcherType = undefined;
    this.fetcher = undefined;
    this.dataUnit = undefined;
    this.dataUnitBuilder = undefined;
    this.registerKey = undefined;
    this.entityName = undefined;
    this.messagesBuilder = undefined;
    this._currentFetcher = undefined;
    this._currentDataUnit = undefined;
    this.crudConfig = undefined;
    this._appResourceID = undefined;
  }
  async registerKeyWatcher(newRegisterKey, oldRegisterKey) {
    var _a;
    if (this._currentDataUnit == null) {
      this.loadAttachmentDataUnit();
    }
    if (oldRegisterKey !== newRegisterKey) {
      if (this._currentFetcher instanceof AnexoSistemaFetcher) {
        this._currentFetcher.registerKey = newRegisterKey;
      }
      await ((_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.loadData());
    }
  }
  getAnexoSistemaFetcherInstance() {
    var _a;
    const anexoSistemaFetcher = new AnexoSistemaFetcher(this.entityName, (_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.name);
    anexoSistemaFetcher.registerKey = this.registerKey;
    return anexoSistemaFetcher;
  }
  async initAttach() {
    var _a, _b, _c, _d, _e;
    if (!this.fetcherType && !this.registerKey)
      return;
    if (!this.fetcherType) {
      this.fetcherType = "AnexoSistema";
    }
    this.returnToGridMode();
    if (this.fetcherType === "AnexoSistema") {
      this._currentFetcher = this.getAnexoSistemaFetcherInstance();
      (_a = this._currentDataUnitBuilder) === null || _a === void 0 ? void 0 : _a.initLoaders(this._currentDataUnit, this._currentFetcher, this.returnToGridMode.bind(this));
      await ((_b = this._currentDataUnit) === null || _b === void 0 ? void 0 : _b.loadData());
      return;
    }
    if (this.fetcherType === "Attach") {
      const hasMoreOneItem = ((_c = this.registerKey) === null || _c === void 0 ? void 0 : _c.split("_").length) > 1;
      if (hasMoreOneItem)
        return;
    }
    await ((_d = this._currentDataUnit) === null || _d === void 0 ? void 0 : _d.loadMetadata());
    await ((_e = this._currentDataUnit) === null || _e === void 0 ? void 0 : _e.loadData(undefined, undefined, true, this.registerKey));
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-attach.msg.ts"
  */
  getMessage(key, params) {
    if (this.messagesBuilder)
      return this.messagesBuilder.getMessage(key, params);
  }
  showFinishedToast() {
    this._application.info(this.getMessage('snkAttach.finishedMessage'), { iconName: "check" });
  }
  downloadAttachment(selectedRecord) {
    if (!selectedRecord)
      throw new Error(this.getMessage("snkAttach.alertValidation.noRecordSelected.message"));
    if (selectedRecord.LINK) {
      window.open(`${selectedRecord.LINK}`);
      return;
    }
    this._currentFetcher
      .getDownloadKey(selectedRecord)
      .then(({ chave }) => {
      var _a;
      let forceDownload = false;
      if (!((_a = selectedRecord === null || selectedRecord === void 0 ? void 0 : selectedRecord.ARQUIVO) === null || _a === void 0 ? void 0 : _a.endsWith(".pdf"))) {
        forceDownload = true;
      }
      window.open(`/mge/visualizadorArquivos.mge?chaveArquivo=${chave.valor}${forceDownload ? "&forcarDownload=S" : ""}`);
    });
  }
  returnToGridMode() {
    var _a;
    (_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.clearSelection();
    if (this._crudElement)
      this._crudElement.goToView(VIEW_MODE.GRID);
  }
  async loadAttachmentDataUnit() {
    try {
      switch (this.fetcherType) {
        case "AnexoSistema":
          await this.loadAnexoSistema();
          break;
        case "Attach":
          await this.loadAttach();
          break;
        default:
          this._currentFetcher = this.fetcher;
          this._currentDataUnit = this.dataUnit;
          this._currentDataUnitBuilder = this.dataUnitBuilder;
      }
    }
    catch (error) {
      throw new Error('There was an error while creating the data unit');
    }
  }
  async loadAnexoSistema() {
    var _a, _b;
    this._currentDataUnit = new DataUnitFetcher().getDataUnit(RESOURCE_ID, DATA_UNIT_NAME);
    this._currentFetcher = this.getAnexoSistemaFetcherInstance();
    let gridValidateForm;
    if (!this._currentDataUnit.metadata) {
      await ((_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.loadMetadata());
      this.crudConfig = this.entityName ? { form: anexoSistemaCrudConfig === null || anexoSistemaCrudConfig === void 0 ? void 0 : anexoSistemaCrudConfig.form } : Object.assign({}, anexoSistemaCrudConfig);
      gridValidateForm = { grid: anexoSistemaCrudConfig === null || anexoSistemaCrudConfig === void 0 ? void 0 : anexoSistemaCrudConfig.grid };
    }
    this.initDataUnitLoaders();
    this._currentDataUnit.addFilterProvider({
      getFilter: () => this._currentDataUnitBuilder.getFilters(this.registerKey)
    });
    this._currentDataUnit.addInterceptor({
      interceptAction: (action) => this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit, action, this._crudElement)
    });
    await ((_b = this._currentDataUnit) === null || _b === void 0 ? void 0 : _b.loadData());
    this.disableEditFieldsNotInForm(gridValidateForm);
  }
  async loadAttach() {
    var _a, _b;
    this._currentFetcher = new AttachFetcher();
    this._currentDataUnit = new DataUnit(InMemoryLoader.IN_MEMORY_DATA_UNIT_NAME);
    this._currentDataUnit.pageSize = 150;
    let gridValidateForm;
    this.initDataUnitLoaders();
    this._currentDataUnit.addInterceptor({
      interceptAction: (action) => {
        var _a;
        if (action.type === Action.METADATA_LOADED) {
          this.crudConfig = this.entityName ? { form: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.form } : Object.assign({}, attachCrudConfig);
          gridValidateForm = { grid: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.grid };
          (_a = this._crudElement) === null || _a === void 0 ? void 0 : _a.updateConfig();
        }
        return this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit, action, this._crudElement);
      }
    });
    if (!this._currentDataUnit.metadata) {
      await ((_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.loadMetadata());
      this.crudConfig = this.entityName ? { form: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.form } : Object.assign({}, attachCrudConfig);
      gridValidateForm = { grid: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.grid };
      await ((_b = this._currentDataUnit) === null || _b === void 0 ? void 0 : _b.loadData(undefined, undefined, true, this.registerKey));
      this.disableEditFieldsNotInForm(gridValidateForm);
    }
  }
  initDataUnitLoaders() {
    var _a, _b;
    if (this.fetcherType === "AnexoSistema") {
      this._currentFetcher = this.getAnexoSistemaFetcherInstance();
      this._currentDataUnitBuilder = new AnexoSistemaDataUnitFactory(this.entityName, this.getMessage.bind(this));
      (_a = this._currentDataUnitBuilder) === null || _a === void 0 ? void 0 : _a.initLoaders(this._currentDataUnit, this._currentFetcher, this.returnToGridMode.bind(this));
    }
    if (this.fetcherType === "Attach") {
      this._currentFetcher = new AttachFetcher();
      this._currentDataUnitBuilder = new AttachFetcherDataUnitFactory(this.getMessage.bind(this));
      (_b = this._currentDataUnitBuilder) === null || _b === void 0 ? void 0 : _b.initLoaders(this._currentDataUnit, this._currentFetcher, async () => {
        this.returnToGridMode();
        await this._currentDataUnit.loadData(undefined, undefined, true, this.registerKey);
      });
    }
  }
  disableEditFieldsNotInForm(gridValidateForm) {
    var _a, _b, _c, _d, _e;
    const gridColumns = ((_b = (_a = this._crudElement) === null || _a === void 0 ? void 0 : _a.gridConfig) === null || _b === void 0 ? void 0 : _b.columns) || ((_c = gridValidateForm === null || gridValidateForm === void 0 ? void 0 : gridValidateForm.grid) === null || _c === void 0 ? void 0 : _c.columns) || ((_e = (_d = this.crudConfig) === null || _d === void 0 ? void 0 : _d.grid) === null || _e === void 0 ? void 0 : _e.columns);
    if (!!this.getGridLegacyConfigName()) {
      this._currentDataUnit.disableField(LINKORFILE_COLUMN_NAME);
    }
    gridColumns === null || gridColumns === void 0 ? void 0 : gridColumns.forEach(column => {
      var _a, _b;
      const fieldName = column.name;
      if (!((_b = (_a = this.crudConfig) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.fields.some(field => (field === null || field === void 0 ? void 0 : field.name) === fieldName))) {
        this._currentDataUnit.disableField(fieldName);
      }
    });
  }
  validateAnexoSistema() {
    var _a;
    if (this._currentFetcher instanceof AnexoSistemaFetcher) {
      try {
        let fields = this._currentDataUnit.getSelectedRecord();
        fields = Object.assign(Object.assign({}, fields), { NOMEARQUIVO: (_a = fields.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0] });
        this._currentFetcher.validateFields(fields);
      }
      catch (error) {
        if (error.message === SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.title'), this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.message'));
          return false;
        }
        if (error.message === SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.title'), this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.message'));
          return false;
        }
      }
    }
    return true;
  }
  async componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    if (this._application) {
      this._appResourceID = await this._application.getResourceID();
    }
    await this.initAttach();
  }
  componentWillRender() {
    if (!this.fetcherType) {
      this.fetcherType = "AnexoSistema";
    }
    if (this._currentDataUnit == null) {
      this.loadAttachmentDataUnit();
    }
  }
  async handleOnDataStateChange({ detail }) {
    if (this.fetcherType !== 'Attach')
      return;
    if (!detail.insertionMode) {
      this._currentDataUnit.disableField('DESCRICAO');
    }
    else {
      this._currentDataUnit.enableField('DESCRICAO');
    }
    await this._currentDataUnit.loadMetadata();
  }
  ;
  isScreenVariation() {
    var _a;
    return !!((_a = this._appResourceID) === null || _a === void 0 ? void 0 : _a.includes('__'));
  }
  getGridLegacyConfigName() {
    if (this.isScreenVariation()) {
      return undefined;
    }
    if (this.gridLegacyConfigName)
      return this.gridLegacyConfigName;
    return this.entityName ? GRID_LEGACY_CONFIG_NAME + "." + this.entityName : this.entityName;
  }
  render() {
    var _a, _b;
    if (!this._currentDataUnit)
      return null;
    return (h("main", { class: "snk-attach__main" }, h("header", { class: "snk-attach__header" }, h("snk-simple-bar", { onExit: this.handleBack, messagesBuilder: this.messagesBuilder }, h("div", { slot: "rightSlot" }, h("ez-button", { class: "ez-button--primary", label: this.getMessage("snkAttach.finish"), onClick: this.handleFinish })))), h("div", { class: "snk-attach__crud-section ez-size-height--full ez-size-width--full ez-flex ez-flex--column" }, h("div", { class: "ez-box__container" }, h("snk-simple-crud", { ref: (el) => this._crudElement = el, dataUnit: this._currentDataUnit, taskbarManager: buildTaskBarManager(), gridConfig: (_a = this.crudConfig) === null || _a === void 0 ? void 0 : _a.grid, formConfig: (_b = this.crudConfig) === null || _b === void 0 ? void 0 : _b.form, useCancelConfirm: false, onActionClick: this.handleTaskbarClick, messagesBuilder: this.messagesBuilder, onDataStateChange: this.handleOnDataStateChange.bind(this), multipleSelection: true, configName: this.isScreenVariation() ? undefined : (this.entityName ? "AnexoSistema_" + this.entityName : undefined), gridLegacyConfigName: this.getGridLegacyConfigName(), ignoreReadOnlyFormFields: this.entityName ? true : false }, h("div", { slot: "snkSimpleCrudHeader" }, h("div", { class: "ez-flex ez-flex--column" }, h("span", { class: "ez-title--primary ez-text ez-text--large ez-text--bold ez-padding-bottom--medium" }, this.getMessage("snkAttach.title")), h("span", { class: "ez-text ez-text--medium ez-text--secondary ez-padding-bottom--medium" }, this.getMessage("snkAttach.description")))))))));
  }
  static get is() { return "snk-attach"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-attach.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-attach.css"]
    };
  }
  static get properties() {
    return {
      "gridLegacyConfigName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Chave da configura\u00E7\u00E3o legado da grid."
        },
        "attribute": "grid-legacy-config-name",
        "reflect": false
      },
      "fetcherType": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "TFetcherType",
          "resolved": "\"AnexoSistema\" | \"Another\" | \"Attach\"",
          "references": {
            "TFetcherType": {
              "location": "import",
              "path": "./interfaces/TFetcherType"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "FetcherType define o tipo de fetcher respons\u00E1vel por carregar os dados do DataUnit."
        },
        "attribute": "fetcher-type",
        "reflect": false
      },
      "fetcher": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "AttachFetcherFacadeInterface",
          "resolved": "AttachFetcherFacadeInterface",
          "references": {
            "AttachFetcherFacadeInterface": {
              "location": "import",
              "path": "../../lib"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Fetcher respons\u00E1vel por carregar os dados do DataUnit."
        }
      },
      "dataUnit": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "DataUnit respons\u00E1vel por carregar os dados."
        }
      },
      "dataUnitBuilder": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "FetcherFacade",
          "resolved": "FetcherFacade",
          "references": {
            "FetcherFacade": {
              "location": "import",
              "path": "./structure"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "DataUnitBuilder respons\u00E1vel por implementar dados a serem utilizados no DataUnit."
        }
      },
      "registerKey": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": true,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Identifica\u00E7\u00E3o do registro pai."
        },
        "attribute": "register-key",
        "reflect": false
      },
      "entityName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Nome da entidade \u00E0 ser utilizada para relacionar o anexo ao DataUnit pai."
        },
        "attribute": "entity-name",
        "reflect": false
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por flexibilizar e padronizar o uso de mensagens nos blocos de constru\u00E7\u00E3o."
        }
      }
    };
  }
  static get states() {
    return {
      "_currentFetcher": {},
      "_currentDataUnit": {},
      "crudConfig": {},
      "_appResourceID": {}
    };
  }
  static get events() {
    return [{
        "method": "back",
        "name": "back",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Evento disparado quando o usu\u00E1rio clica no bot\u00E3o voltar."
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get watchers() {
    return [{
        "propName": "registerKey",
        "methodName": "registerKeyWatcher"
      }];
  }
}
