import { r as registerInstance, f as createEvent, h, d as getElement } from './index-cb74209c.js';
import { f as findOrCreateOnReady } from './utils-0af5fee1.js';

const LikeButton = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.glLike = 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 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 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 (h("ion-button", { fill: "clear", onClick: this.likeClicked, disabled: this.disabled }, h("ion-icon", { slot: "start", name: this.liked ? this.iconYes : this.iconNo }), h("span", { class: "gl-like-button-count" }, this.count)));
  }
  get el() { return getElement(this); }
  static get watchers() { return {
    "feature": ["setState"]
  }; }
};

export { LikeButton as gl_like_button };

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