import { r as registerInstance, e as createEvent, c as getConnect, h, d as getElement } from './chunk-eb0263ab.js';

class LikeButton {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.count = 0;
        this.liked = false;
        this.attribute = '_likes';
        this.disabled = false;
        this.iconNo = 'star-outline';
        this.iconYes = 'star';
        this.method = 'POST';
        this.glLike = createEvent(this, "glLike", 7);
        this.likeCtrl = getConnect(this, "gl-like-controller");
        this.restCtrl = getConnect(this, "gl-rest-controller");
    }
    async componentWillLoad() {
        await this.setState();
    }
    async setState() {
        if (this.feature) {
            this.count = this.feature.properties[this.attribute];
            this.proxy = await this.likeCtrl.create(this.feature);
            this.liked = this.proxy.isLiked();
        }
    }
    async toggle() {
        this.liked = !this.liked;
        this.count += (this.liked) ? 1 : -1;
        if (this.feature && this.feature.properties)
            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 {
            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: () => {
                if (!this.disabled)
                    this.toggle();
            }, 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 };
