import { FetchHelper } from "../../../globals/FetchHelper";
import { LocalStorageService } from "../../../globals/LocalStorageService";
export class PnLevelUpService {
    _endpoint;
    _levelupAuthorizePath = `/api/levelup/level-up-authorize`;
    _levelupTokenGrantPath = `/api/levelup/level-up-token-grant`;
    levelupLocalStorageKey = 'levelup';
    fetchHelper = new FetchHelper('PnLevelUpService');
    _storage = new LocalStorageService();
    constructor(endpoint) {
        this._endpoint = this.formatEndpoint(endpoint);
    }
    newLevelupUser() {
        let threeMinutesInMilliseconds = 180000;
        this._storage.set(this.levelupLocalStorageKey, { expire: Date.now() + threeMinutesInMilliseconds });
    }
    async levelupAuthorize(system, defaultReturn) {
        if (!system) {
            return defaultReturn;
        }
        let model = {
            system: system
        };
        const fetchUrl = this._endpoint + this._levelupAuthorizePath;
        const data = (await this.fetchHelper.fetchJson(fetchUrl, this.getRequestInit(model), false));
        return this.handleResponse(data, defaultReturn);
    }
    async levelupTokenGrant(id, loopSeconds, defaultReturn) {
        if (!id) {
            return defaultReturn;
        }
        let model = {
            id: id,
            loopSeconds: loopSeconds
        };
        const fetchUrl = this._endpoint + this._levelupTokenGrantPath;
        const data = (await this.fetchHelper.fetchJson(fetchUrl, this.getRequestInit(model), false));
        return this.handleResponse(data, defaultReturn);
    }
    formatEndpoint(endpoint) {
        return endpoint.lastIndexOf('/') === endpoint.length - 1 ? endpoint.substring(0, endpoint.length - 1) : endpoint;
    }
    handleResponse(data, defaultReturn, checkForArray = false) {
        if (!data) {
            return defaultReturn;
        }
        let parsedData = JSON.parse(data);
        if (!parsedData || checkForArray && !Array.isArray(parsedData)) {
            return defaultReturn;
        }
        return parsedData;
    }
    getRequestInit(model, method = 'POST', mode = 'cors', contentTypes = 'application/json') {
        return {
            mode: mode,
            method: method,
            headers: {
                'Content-Type': contentTypes,
                'CustomValidateAntiForgeryToken': "0111000001101110011000110110000101110100"
            },
            body: JSON.stringify(model)
        };
    }
}
//# sourceMappingURL=pn-level-up.service.js.map
