import { ApplicationContext } from '@sankhyalabs/core';
import { h, Host } from '@stencil/core';
import { SnkMessageBuilder } from '../../lib/message/SnkMessageBuilder';
import { base64ToBlob, buildFileKey, downloadImage, getPKs, sessionFileUpload } from './utils/ImageUtils';
import { Action } from '@sankhyalabs/core';
export class SnkImageInput {
  constructor() {
    this.dataUnitObserver = async (action) => {
      var _a;
      const actionsMoveSelection = [Action.NEXT_SELECTED, Action.PREVIOUS_SELECTED];
      if (actionsMoveSelection.includes(action.type)) {
        await this.loadImage();
        return;
      }
      const selection = ((_a = action.payload) === null || _a === void 0 ? void 0 : _a.selection) || [];
      if (action.type === Action.SELECTION_CHANGED && selection.length > 0) {
        await this.loadImage();
        return;
      }
      if (action.type === Action.RECORDS_ADDED) {
        await this.clearImage();
        return;
      }
      if (action.type === Action.EDITION_CANCELED) {
        await this.loadImage();
        return;
      }
    };
    this.dataUnit = undefined;
    this.fieldName = undefined;
    this.entityName = undefined;
    this.enabled = true;
    this.acceptType = undefined;
    this.maxSize = undefined;
    this.label = undefined;
    this.imageValue = undefined;
    this.loading = true;
  }
  /**
   * Força o reload da imagem
   */
  async reloadImage(pks) {
    await this.loadImage(pks);
  }
  getMessage(key, params) {
    if (!this.messagesBuilder) {
      this.messagesBuilder = new SnkMessageBuilder();
    }
    return this.messagesBuilder.getMessage(key, params);
  }
  async clearImage() {
    var _a;
    (_a = this._loadAbortController) === null || _a === void 0 ? void 0 : _a.abort();
    this.imageValue = undefined;
  }
  async handleImageChange(event) {
    const base64 = event.detail;
    if (!base64) {
      await this.clearImage();
      await this.updatedataUnitField(true);
      return;
    }
    const blob = await base64ToBlob(base64);
    if (this.maxSize && blob.size > this.maxSize * 1024) {
      const errorMsg = this.getMessage('snkImageInput.errorImageSize') + this.maxSize + '(KB)';
      this.imageError.emit(errorMsg);
      if (this.application) {
        await this.application.error(this.getMessage('snkImageInput.errorTitle'), errorMsg);
      }
      return;
    }
    this.imageValue = base64;
    await sessionFileUpload(blob, this.entityName, this.fieldName);
    await this.updatedataUnitField();
  }
  async updatedataUnitField(deleted = false) {
    if (!this.dataUnit || !this.dataUnit.getSelectedRecord()) {
      return;
    }
    if (deleted) {
      await this.dataUnit.setFieldValue(this.fieldName, 'deletado');
    }
    else {
      await this.dataUnit.setFieldValue(this.fieldName, `$file.session.key{${buildFileKey(this.entityName, this.fieldName)}}`);
    }
  }
  async handleImageError(event) {
    this.imageError.emit(event.detail);
    if (this.application) {
      await this.application.error(this.getMessage('snkImageInput.errorTitle'), event.detail);
    }
  }
  getPksFromDataUnit() {
    if (!this.dataUnit) {
      return undefined;
    }
    const selectedRecord = this.dataUnit.getSelectedRecord();
    if (!selectedRecord) {
      return undefined;
    }
    const fieldValue = selectedRecord[this.fieldName];
    if (!fieldValue) {
      return undefined;
    }
    try {
      const pk = JSON.parse(fieldValue);
      return pk;
    }
    catch (error) {
      console.error('Error parsing PK from data unit field:', error);
      return undefined;
    }
  }
  async loadImage(pks) {
    var _a, _b;
    (_a = this._loadAbortController) === null || _a === void 0 ? void 0 : _a.abort();
    const controller = new AbortController();
    this._loadAbortController = controller;
    this.loading = true;
    if (this.dataUnit && this.entityName) {
      pks = (_b = pks !== null && pks !== void 0 ? pks : this.getPksFromDataUnit()) !== null && _b !== void 0 ? _b : getPKs(this.dataUnit);
      const image = await downloadImage(pks, this.fieldName, this.entityName, controller.signal);
      if (controller.signal.aborted)
        return;
      this.imageValue = image;
    }
    this.loading = false;
  }
  async componentWillLoad() {
    this.application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    if (!this.messagesBuilder) {
      this.messagesBuilder = new SnkMessageBuilder();
    }
    if (this.dataUnit) {
      this.dataUnit.subscribe(this.dataUnitObserver);
    }
  }
  disconnectedCallback() {
    if (this.dataUnit) {
      this.dataUnit.unsubscribe(this.dataUnitObserver);
    }
  }
  async componentDidLoad() {
    await this.loadImage();
  }
  render() {
    return (h(Host, null, h("ez-image-input", { enabled: this.enabled, label: this.label, name: this.fieldName, value: this.imageValue, maxFileSize: this.maxSize ? this.maxSize * 1024 : undefined, accept: this.acceptType || 'image/png,image/jpeg,image/gif', onEzChange: (e) => this.handleImageChange(e), onEzError: (e) => this.handleImageError(e), loading: this.loading })));
  }
  static get is() { return "snk-image-input"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-image-input.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-image-input.css"]
    };
  }
  static get properties() {
    return {
      "dataUnit": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "DataUnit associado ao componente"
        }
      },
      "fieldName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Nome do campo no DataUnit"
        },
        "attribute": "field-name",
        "reflect": false
      },
      "entityName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Nome da entidade (usado quando n\u00E3o h\u00E1 DataUnit)"
        },
        "attribute": "entity-name",
        "reflect": false
      },
      "enabled": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se est\u00E1 habilitado"
        },
        "attribute": "enabled",
        "reflect": false,
        "defaultValue": "true"
      },
      "acceptType": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Tipos MIME aceitos (separados por v\u00EDrgula)"
        },
        "attribute": "accept-type",
        "reflect": false
      },
      "maxSize": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Tamanho m\u00E1ximo do arquivo em KB"
        },
        "attribute": "max-size",
        "reflect": false
      },
      "label": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Label do componente"
        },
        "attribute": "label",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "imageValue": {},
      "loading": {}
    };
  }
  static get events() {
    return [{
        "method": "imageError",
        "name": "imageError",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Evento disparado quando h\u00E1 erro"
        },
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "reloadImage": {
        "complexType": {
          "signature": "(pks?: Record<string, any>) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Record": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "For\u00E7a o reload da imagem",
          "tags": []
        }
      }
    };
  }
}
