export class LikeProxy {
    constructor(feature, options = {}) {
        this.feature = feature;
        if (!options.keyPrefix)
            options.keyPrefix = 'webmapgl.like';
        if (!options.clientId) {
            options.clientId = localStorage.getItem(options.keyPrefix + '.clientId');
            if (!options.clientId) {
                options.clientId = this.makeId(64);
                localStorage.setItem(options.keyPrefix + '.clientId', options.clientId);
            }
        }
        this.options = options;
    }
    getClientId() {
        return this.options.clientId;
    }
    isLiked() {
        let likes = this.getArray(this.feature.layer);
        return likes.indexOf(this.feature.id) !== -1;
    }
    like() {
        let likes = this.getArray(this.feature.layer);
        if (likes.indexOf(this.feature.id) === -1)
            likes.push(this.feature.id);
        this.setArray(this.feature.layer, likes);
    }
    unlike() {
        let likes = this.getArray(this.feature.layer);
        let idx = likes.indexOf(this.feature.id);
        if (idx !== -1)
            likes.splice(idx, 1);
        this.setArray(this.feature.layer, likes);
    }
    makeId(length) {
        var id = '';
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +
            '0123456789';
        for (let i = 0; i < length; i++)
            id += chars.charAt(Math.floor(Math.random() * chars.length));
        return id;
    }
    getLayerKey(layer) {
        return this.options.keyPrefix + '|' + document.location.pathname + '|' +
            (layer || 'default');
    }
    getArray(layer) {
        let str = localStorage.getItem(this.getLayerKey(layer));
        if (!str)
            return [];
        return str.split(',').map((v) => parseInt(v)).filter((v) => !isNaN(v));
    }
    setArray(layer, values) {
        let str = values.filter((v) => !isNaN(v))
            .map((v) => v.toString()).join(',');
        localStorage.setItem(this.getLayerKey(layer), str);
    }
}
