/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { b as getAllTables } from "../../chunks/mapViewUtils.js";
import { css, html } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot } from "@arcgis/lumina";
import Graphic from "@arcgis/core/Graphic";
import RelationshipQuery from "@arcgis/core/rest/support/RelationshipQuery";
const styles = css`@layer{
/**
 * @license
 * Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

:host {
  display: block;
}

.buttons-container {
  align-items: center;
  display: flex;
  padding: 4px;
  color: var(--calcite-color-text-1) !important;
  background-color: var(--calcite-color-foreground-1) !important;
  border-block-start: 1px solid var(--calcite-color-border-3);
  border-block-end: 1px solid var(--calcite-color-border-3);
}
}`;
class FeatureDetails extends LitElement {
  constructor() {
    super(...arguments);
    this.enableSnapping = false;
    this.graphics = [];
    this.showUserImageInCommentsList = false;
    this.showFullCommentTitle = true;
    this._likeFieldAvailable = false;
    this._likeCount = 0;
    this._disLikeCount = 0;
    this._dislikeFieldAvailable = false;
    this._commentsAvailable = false;
    this._isLikeBtnClicked = false;
    this._isDislikeBtnClicked = false;
    this._relatedFeaturesOIDs = [];
    this._updating = false;
    this._infoCard = createRef();
    this._commentsList = createRef();
    this._likeField = "";
    this._dislikeField = "";
    this._validFieldTypes = ["small-integer", "integer", "big-integer", "single", "long"];
    this.relatedTableId = "";
    this.loadingStatus = createEvent();
    this.commentClick = createEvent();
    this.commentSelect = createEvent();
    this.addComment = createEvent();
    this.likeOrDislikeClicked = createEvent();
    this.featureSelectionChange = createEvent();
  }
  static {
    this.properties = { enableSnapping: [5, {}, { type: Boolean }], mapView: [0, {}, { attribute: false }], graphics: [0, {}, { attribute: false }], reportingOptions: [0, {}, { attribute: false }], layerItemsHash: [0, {}, { attribute: false }], showUserImageInCommentsList: [5, {}, { type: Boolean }], showFullCommentTitle: [5, {}, { type: Boolean }], _likeFieldAvailable: [16, {}, { state: true }], _likeCount: [16, {}, { state: true }], _disLikeCount: [16, {}, { state: true }], _dislikeFieldAvailable: [16, {}, { state: true }], _commentsAvailable: [16, {}, { state: true }], _isLikeBtnClicked: [16, {}, { state: true }], _isDislikeBtnClicked: [16, {}, { state: true }], _relatedFeaturesOIDs: [16, {}, { state: true }], _updating: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("graphics")) {
      void this.graphicsWatchHandler();
    }
  }
  async graphicsWatchHandler() {
    await this.getCompleteGraphic(this.graphics[0]);
    this.checkLikeDislikeFields();
    await this.processComments();
  }
  async refresh(graphic) {
    graphic && await this.getCompleteGraphic(graphic);
    await this.processComments();
    if (graphic && this.isLikeDislikeConfigured(graphic.layer)) {
      if (this.graphics.length > 1) {
        this.checkLikeDislikeFields();
      }
    } else {
      this._likeFieldAvailable = false;
      this._dislikeFieldAvailable = false;
    }
  }
  async back() {
    this._infoCard.value && void this._infoCard.value.back();
  }
  async next() {
    this._infoCard.value && void this._infoCard.value.next();
  }
  async toggleListView() {
    this._infoCard.value && void this._infoCard.value.toggleListView();
  }
  async load() {
    await this.getCompleteGraphic(this.graphics[0]);
    this.checkLikeDislikeFields();
    await this.processComments();
  }
  render() {
    const commentsListWhereClause = this._relatedFeaturesOIDs?.length > 0 ? `objectId in(${this._relatedFeaturesOIDs})` : "1=0";
    return html`<calcite-panel><info-card .enableSnapping=${this.enableSnapping} .graphics=${this.graphics} .mapView=${this.mapView} @selectionChanged=${(e) => {
      this.featureSelectionChange.emit(e.detail);
    }} position=relative ${ref(this._infoCard)}></info-card>${(this._likeFieldAvailable || this._dislikeFieldAvailable || this._commentsAvailable) && html`<div class="buttons-container">${this._commentsAvailable && html`<calcite-button appearance=transparent icon-end=speech-bubble kind=neutral @click=${() => {
      this.addComment.emit();
    }} scale=m>${this._relatedFeaturesOIDs.length}</calcite-button>` || ""}${this._likeFieldAvailable && html`<calcite-button appearance=transparent icon-end=thumbs-up .kind=${this._isLikeBtnClicked ? "brand" : "neutral"} .loading=${this._updating} @click=${this.onLikeButtonClick} scale=m>${this._likeCount ?? this._selectedGraphic?.attributes[this._likeField] ?? 0}</calcite-button>` || ""}${this._dislikeFieldAvailable && html`<calcite-button appearance=transparent icon-end=thumbs-down .kind=${this._isDislikeBtnClicked ? "brand" : "neutral"} .loading=${this._updating} @click=${this.onDislikeButtonClick} scale=m>${this._disLikeCount ?? this._selectedGraphic?.attributes[this._dislikeField] ?? 0}</calcite-button>` || ""}</div>` || ""}${this.relatedTableId && this._commentsAvailable && html`<feature-list class="height-full" .mapView=${this.mapView} @featureClick=${() => {
      this.commentClick.emit();
    }} @featureSelect=${(e) => {
      this.commentSelect.emit(e.detail);
    }} page-size=5 .selectedLayerId=${this.relatedTableId} .showFullTitle=${this.showFullCommentTitle} .showUserImageInList=${this.showUserImageInCommentsList} text-size=small .whereClause=${commentsListWhereClause} ${ref(this._commentsList)}></feature-list>` || ""}</calcite-panel>`;
  }
  async getCompleteGraphic(graphic) {
    if (graphic) {
      const layer = graphic.layer;
      const query = layer.createQuery();
      const oid = Number(graphic.getObjectId());
      if (!Number.isNaN(oid)) {
        query.objectIds = [oid];
        const completeGraphic = await layer.queryFeatures(query);
        this._selectedGraphic = completeGraphic.features[0];
      }
    }
  }
  async processComments() {
    const selectedLayer = this._selectedGraphic?.layer;
    const commentsConfigured = this.reportingOptions && this.reportingOptions[selectedLayer.id] && this.reportingOptions[selectedLayer.id].comment && selectedLayer?.relationships && selectedLayer.relationships?.length > 0;
    if (commentsConfigured) {
      const allTables = this.mapView && await getAllTables(this.mapView);
      let relatedTable = null;
      let validRelationshipId = null;
      selectedLayer?.relationships?.some((relationship) => {
        const relatedTables = allTables?.filter((table) => selectedLayer.url === table.url && table.layerId === relationship.relatedTableId);
        if (relatedTables && relatedTables.length > 0) {
          relatedTable = relatedTables[0];
          validRelationshipId = relationship.id;
          return true;
        } else {
          return false;
        }
      });
      this.relatedTableId = relatedTable?.id ?? "";
      if (this.relatedTableId) {
        const objectId = this._selectedGraphic?.attributes[selectedLayer?.objectIdField];
        const relationshipQuery = new RelationshipQuery({
          objectIds: [objectId],
          outFields: ["*"],
          relationshipId: validRelationshipId
        });
        const result = relationshipQuery && await selectedLayer.queryRelatedFeatures(relationshipQuery).catch((e) => {
          console.error(e);
        });
        const relatedOIDs = [];
        if (result && result[objectId]) {
          result[objectId].features.forEach((feature) => {
            relatedOIDs.push(feature.attributes[relatedTable.objectIdField]);
          });
        }
        this._relatedFeaturesOIDs = relatedOIDs;
        this._commentsAvailable = true;
      } else {
        this._relatedFeaturesOIDs = [];
        this._commentsAvailable = false;
      }
    } else {
      this._relatedFeaturesOIDs = [];
      this._commentsAvailable = false;
      this.relatedTableId = "";
    }
  }
  isLikeDislikeConfigured(selectedLayer) {
    let likeFieldAvailable = false;
    let dislikeFieldAvailable = false;
    if (this.reportingOptions && selectedLayer && this.reportingOptions[selectedLayer.id]) {
      if (!this.reportingOptions[selectedLayer.id].like && !this.reportingOptions[selectedLayer.id].dislike) {
        return false;
      }
      const likeField = this.reportingOptions[selectedLayer.id].likeField;
      const dislikeField = this.reportingOptions[selectedLayer.id].dislikeField;
      if (!likeField && !dislikeField) {
        return false;
      }
      selectedLayer.fields.forEach((eachField) => {
        if (this._validFieldTypes.indexOf(eachField.type) > -1 && this.layerItemsHash && this.reportingOptions && this.layerItemsHash[selectedLayer.id].supportsUpdate) {
          if (eachField.name === likeField && this.reportingOptions[selectedLayer.id].like) {
            likeFieldAvailable = true;
          } else if (eachField.name === dislikeField && this.reportingOptions[selectedLayer.id].dislike) {
            dislikeFieldAvailable = true;
          }
        }
      });
    }
    return likeFieldAvailable || dislikeFieldAvailable;
  }
  checkLikeDislikeFields() {
    this._likeFieldAvailable = false;
    this._dislikeFieldAvailable = false;
    this._isLikeBtnClicked = false;
    this._isDislikeBtnClicked = false;
    this._likeCount = 0;
    this._disLikeCount = 0;
    const selectedLayer = this._selectedGraphic?.layer;
    if (this.reportingOptions && selectedLayer && this.reportingOptions[selectedLayer?.id]) {
      this._likeField = this.reportingOptions[selectedLayer.id].likeField || "";
      this._dislikeField = this.reportingOptions[selectedLayer.id].dislikeField || "";
      if (!this._likeField && !this._dislikeField) {
        return;
      }
      selectedLayer.fields.forEach((eachField) => {
        if (this._validFieldTypes.indexOf(eachField.type) > -1 && this.layerItemsHash && this.reportingOptions && this.layerItemsHash[selectedLayer.id].supportsUpdate) {
          if (eachField.name === this._likeField && this.reportingOptions[selectedLayer.id].like) {
            this._likeFieldAvailable = true;
            this._likeCount = this._selectedGraphic?.attributes[eachField.name] || 0;
          } else if (eachField.name === this._dislikeField && this.reportingOptions[selectedLayer.id].dislike) {
            this._dislikeFieldAvailable = true;
            this._disLikeCount = this._selectedGraphic?.attributes[eachField.name] || 0;
          }
        }
      });
      this.getFromLocalStorage();
    }
  }
  onLikeButtonClick() {
    if (this._isDislikeBtnClicked && this._selectedGraphic?.layer && this.reportingOptions && this.reportingOptions[this._selectedGraphic.layer.id].dislike) {
      this.onDislikeButtonClick();
    }
    this._isLikeBtnClicked = !this._isLikeBtnClicked;
    if (this._isLikeBtnClicked) {
      this._likeCount++;
    } else {
      this._likeCount--;
    }
    void this.updateFeaturesLikeDislikeField(this._likeField, this._isLikeBtnClicked);
  }
  onDislikeButtonClick() {
    if (this._isLikeBtnClicked && this._selectedGraphic?.layer && this.reportingOptions && this.reportingOptions[this._selectedGraphic.layer.id].like) {
      this.onLikeButtonClick();
    }
    this._isDislikeBtnClicked = !this._isDislikeBtnClicked;
    if (this._isDislikeBtnClicked) {
      this._disLikeCount++;
    } else {
      this._disLikeCount--;
    }
    void this.updateFeaturesLikeDislikeField(this._dislikeField, this._isDislikeBtnClicked);
  }
  async updateFeaturesLikeDislikeField(fieldName, buttonClicked) {
    const attributesToUpdate = {};
    const selectedLayer = this._selectedGraphic?.layer;
    this._updating = true;
    const selectFeatureAttr = this._selectedGraphic;
    if (selectFeatureAttr) {
      selectFeatureAttr.attributes[fieldName] = Number(selectFeatureAttr.attributes[fieldName]) + (buttonClicked ? 1 : -1);
      attributesToUpdate[selectedLayer.objectIdField] = selectFeatureAttr.attributes[selectedLayer.objectIdField];
      attributesToUpdate[fieldName] = selectFeatureAttr.attributes[fieldName];
      const newGraphicInstance = new Graphic();
      if (newGraphicInstance) {
        newGraphicInstance.attributes = attributesToUpdate;
        const param = { updateFeatures: [newGraphicInstance] };
        await selectedLayer.applyEdits(param).then(() => {
          this._selectedGraphic = selectFeatureAttr;
          this.setInLocalStorage();
          this._updating = false;
          this.likeOrDislikeClicked.emit();
        }, (err) => {
          this._updating = false;
          console.log(err);
        });
      }
    }
  }
  getFromLocalStorage() {
    const uniqueLayerId = this._selectedGraphic?.layer && this._selectedGraphic.layer.id;
    const localStorageUser = uniqueLayerId?.toString() && localStorage[uniqueLayerId];
    if (localStorageUser) {
      const parseArr = JSON.parse(localStorageUser);
      const res = parseArr.filter((arr) => arr.id === this._selectedGraphic?.getObjectId());
      if (res.length > 0) {
        this._isLikeBtnClicked = res[0].like;
        this._isDislikeBtnClicked = res[0].dislike;
      }
    }
  }
  setInLocalStorage() {
    const uniqueLayerId = this._selectedGraphic?.layer && this._selectedGraphic.layer.id;
    const localStorageInfo = uniqueLayerId?.toString() && localStorage[uniqueLayerId];
    let information = [];
    if (localStorageInfo) {
      information = JSON.parse(localStorageInfo);
      const index = information.findIndex((arr) => arr.id === this._selectedGraphic?.getObjectId());
      if (index >= 0) {
        information.splice(index, 1);
      }
    }
    information.push({
      id: this._selectedGraphic?.getObjectId(),
      like: this._isLikeBtnClicked && this._likeCount !== 0,
      dislike: this._isDislikeBtnClicked && this._disLikeCount !== 0
    });
    if (uniqueLayerId?.toString()) {
      localStorage.setItem(uniqueLayerId.toString(), JSON.stringify(information));
    }
  }
}
customElement("feature-details", FeatureDetails);
export {
  FeatureDetails
};
