'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-b8c5f2d4.js');
const utils = require('./utils-94ef970a.js');

const LikeButton = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.glLike = index.createEvent(this, "glLike", 7);
    this.likeClicked = () => {
      if (!this.disabled)
        this.toggle();
    };
    this.count = 0;
    this.liked = false;
    this.proxy = undefined;
    this.likeCtrl = undefined;
    this.restCtrl = undefined;
    this.attribute = "_likes";
    this.disabled = false;
    this.feature = undefined;
    this.iconNo = "star-outline";
    this.iconYes = "star";
    this.method = "POST";
    this.requestMode = undefined;
    this.token = undefined;
    this.url = undefined;
  }
  async componentWillLoad() {
    await this.setState();
  }
  async setState() {
    if (this.feature != undefined) {
      this.count = this.feature.properties[this.attribute];
      if (this.likeCtrl == undefined) {
        this.likeCtrl = await utils.findOrCreateOnReady("gl-like-controller");
      }
      this.proxy = await this.likeCtrl.create(this.feature);
      this.liked = this.proxy.isLiked();
    }
  }
  async toggle() {
    var _a;
    this.liked = !this.liked;
    this.count += this.liked ? 1 : -1;
    if (((_a = this.feature) === null || _a === void 0 ? void 0 : _a.properties) != undefined)
      this.feature.properties[this.attribute] = this.count;
    this.liked ? this.proxy.like() : this.proxy.unlike();
    // Fail silently if request fails.
    let success = false;
    let clientId = this.proxy.getClientId();
    try {
      if (this.restCtrl == undefined) {
        this.restCtrl = await utils.findOrCreateOnReady("gl-rest-controller");
      }
      await this.restCtrl.create({
        type: "Feature",
        properties: {
          action: this.liked ? "like" : "unlike",
          feature_id: this.feature.id,
          client_id: clientId,
        },
      }, {
        url: this.url,
        token: this.token,
        method: this.method,
        mode: this.requestMode,
      });
      success = true;
    }
    catch (e) { }
    this.glLike.emit({
      success: success,
      feature: this.feature,
      action: this.liked ? "like" : "unlike",
      client_id: clientId,
    });
  }
  render() {
    return (index.h("ion-button", { fill: "clear", onClick: this.likeClicked, disabled: this.disabled }, index.h("ion-icon", { slot: "start", name: this.liked ? this.iconYes : this.iconNo }), index.h("span", { class: "gl-like-button-count" }, this.count)));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "feature": ["setState"]
  }; }
};

exports.gl_like_button = LikeButton;

//# sourceMappingURL=gl-like-button.cjs.entry.js.map