import { DvnDataAdapter } from '@dvn/core/adapters/DvnDataAdapter';
import { DataApiImpl } from '@dvn/core/api/dataApi';
import { renderReference } from '@dvn/core/doldurma/src/fields/reference/dvn-field-display-cell-reference/util';
import { DvnDataProvider } from '@dvn/core/providers/DvnDataProvider';
import { getSessionData } from '@dvn/kimlik/index';
import { Component, Event, h, Host, Listen, Prop, State } from '@stencil/core';
// TODO remove this?
const dataApiEndpoint = () => {
  let env = 'prod';
  let base = 'mentornity';
  if (window.location.hostname === 'console.qa-one.mentornity.com') {
    env = 'qa';
    base = 'mentornity-qa';
  }
  return `/api-data/${env}/${base}/`;
};
export class DvnFieldInputCellReference {
  onAction(event) {
    if (event.detail.name === 'dvn-field-input-cell-reference.remove-item') {
      event.stopImmediatePropagation();
      const itemToRemove = event.detail.params.item;
      this.internalValue = this.internalValue.filter(item => item._id !== itemToRemove._id);
    }
  }
  componentWillLoad() {
    this.internalValue = this.value || [];
    this.dataProvider = getDataProvider(this.field);
  }
  render() {
    const { field, internalValue, meta } = this;
    const value = this.value || [];
    return (h(Host, null,
      Array.isArray(value)
        ? value.map(data => renderReference(field, data, meta))
        : renderReference(field, value, meta),
      h("dvn-dialog", { shown: true, onDismiss: () => this.cellFormCancel.emit() },
        h("dvn-select", { dataAdapter: new DvnDataAdapter(field.titleField, '_id'), dataProvider: this.dataProvider, onChange: (e) => {
            var _a, _b;
            e.stopImmediatePropagation();
            const item = (_b = (_a = this.dataProvider.list) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.find(item => item._id === e.detail);
            this.internalValue = [...this.internalValue, item];
          }, leaned: true, width: "100%", value: [] }),
        h("dvn-list-view-table", { config: {
            hideHeader: true,
            separation: 1,
            actions: [{
                ui: {
                  name: 'dvn-field-input-cell-reference.remove-item',
                  buttonType: 'icon-button',
                  iconName: 'uil uil-trash-alt',
                  tint: 'danger',
                  view: 'flat'
                }
              }],
            fields: [
              { fieldId: field.imageField },
              { fieldId: field.titleField },
            ],
            columns: {
              [field.imageField]: {
                width: 50,
              },
            },
          }, fields: field.fields, items: internalValue, isEndReached: true }),
        h("div", { slot: "actions" },
          h("dvn-button", { view: "flat", onClick: (e) => {
              e.stopImmediatePropagation();
              this.cellFormCancel.emit();
            } }, "Cancel"),
          h("dvn-button", { tint: "primary", view: "flat", onClick: (e) => {
              e.stopImmediatePropagation();
              this.cellFormSubmit.emit({
                value: this.internalValue,
                apiValue: this.internalValue.map(item => convertToRef(field, item)),
              });
            } }, "Save")))));
  }
  static get is() { return "dvn-field-input-cell-reference"; }
  static get originalStyleUrls() { return {
    "$": ["dvn-field-input-cell-reference.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["dvn-field-input-cell-reference.css"]
  }; }
  static get properties() { return {
    "value": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "any[]",
        "resolved": "any[]",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "field": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "ReferenceField",
        "resolved": "ReferenceField",
        "references": {
          "ReferenceField": {
            "location": "import",
            "path": "../reference-field"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "meta": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{ imageShape: ImageShape }",
        "resolved": "{ imageShape: ImageShape; }",
        "references": {
          "ImageShape": {
            "location": "import",
            "path": "@dvn/alaca/components/dvn-image/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "internalValue": {}
  }; }
  static get events() { return [{
      "method": "cellFormCancel",
      "name": "cellFormCancel",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "cellFormSubmit",
      "name": "cellFormSubmit",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get listeners() { return [{
      "name": "action",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
function getDataProvider(field) {
  const dataApi = new DataApiImpl(dataApiEndpoint(), { Authorization: `Bearer ${getSessionData().token}` });
  return new DvnDataProvider(dataApi, field.otherCollection, {
    fields: field.fields,
    sort: [{ id: field.titleField, order: 1 }]
  }, undefined, {
    fields: [
      { fieldId: field.imageField },
      { fieldId: field.titleField },
    ]
  });
}
function convertToRef(field, { _id }) {
  return {
    _ref: field.otherCollection,
    _id,
  };
}
