"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIEndpoint = exports.API_DATE_FORMAT = void 0;
const dayjs_1 = __importDefault(require("dayjs"));
const config_1 = require("../config");
const MemberPortalFeature_1 = __importDefault(require("../providers/feature/MemberPortalFeature"));
const RoomstayThemeEngine_1 = __importDefault(require("../providers/RoomstayThemeEngine"));
const AsyncAuth_1 = require("../util/AsyncAuth");
exports.API_DATE_FORMAT = 'YYYY-MM-DD';
var APIEndpoint;
(function (APIEndpoint) {
    APIEndpoint["Availability"] = "availability";
    APIEndpoint["Calendar"] = "availability/calendar";
    APIEndpoint["MinNightStay"] = "availability/min-nights";
    APIEndpoint["AreaAvailability"] = "availability/areas";
    APIEndpoint["Reservations"] = "reservations";
    APIEndpoint["Packages"] = "packages";
    APIEndpoint["Member"] = "member";
    APIEndpoint["Session"] = "session";
})(APIEndpoint || (exports.APIEndpoint = APIEndpoint = {}));
class BaseAPI {
    constructor() {
        this.post = (endpoint_1, params_1, hotelID_1, getParams_1, ...args_1) => __awaiter(this, [endpoint_1, params_1, hotelID_1, getParams_1, ...args_1], void 0, function* (endpoint, params, hotelID, getParams, extraPath = '') { return this.postOrDeleteOrUpdate('POST', endpoint, params, getParams, extraPath, hotelID); });
        this.delete = (endpoint_1, params_1, hotelID_1, getParams_1, ...args_1) => __awaiter(this, [endpoint_1, params_1, hotelID_1, getParams_1, ...args_1], void 0, function* (endpoint, params, hotelID, getParams, extraPath = '') { return this.postOrDeleteOrUpdate('DELETE', endpoint, params, getParams, extraPath, hotelID); });
        this.get = (endpoint_1, params_1, ...args_1) => __awaiter(this, [endpoint_1, params_1, ...args_1], void 0, function* (endpoint, params, extraPath = '', hotelId) {
            if (!params.language) {
                params.language = RoomstayThemeEngine_1.default.selectedLang;
            }
            const parameters = this.formatParams(params);
            const response = yield fetch(this.getUrl(endpoint, hotelId) + extraPath + (parameters ? '?' + parameters : ''), {
                headers: yield BaseAPI.getBaseHeaders(),
            });
            const json = yield response.json();
            if (response.ok) {
                return json;
            }
            else {
                throw json;
            }
        });
        this.getUrl = (endpoint, hotelId) => {
            return `${this.getApiPath()}${endpoint}/${hotelId ? `${hotelId}/` : ''}`;
        };
        this.postOrDeleteOrUpdate = (method_1, endpoint_1, params_1, ...args_1) => __awaiter(this, [method_1, endpoint_1, params_1, ...args_1], void 0, function* (method, endpoint, params, getParams = {}, extraPath = '', hotelID) {
            if (!getParams.language) {
                getParams.language = RoomstayThemeEngine_1.default.selectedLang;
            }
            const getParamsAsString = this.formatParams(getParams);
            const bodyParams = this.formatParams(params, false);
            const response = yield fetch(this.getUrl(endpoint, hotelID) + extraPath + (getParamsAsString ? `?${getParamsAsString}` : ''), {
                credentials: 'omit',
                headers: yield BaseAPI.getBaseHeaders(),
                method,
                body: JSON.stringify(bodyParams),
            });
            if (response.ok) {
                return response.json();
            }
            else {
                throw yield response.json();
            }
        });
    }
    static getBaseHeaders() {
        return __awaiter(this, void 0, void 0, function* () {
            const baseHeaders = {
                'Content-Type': 'application/json',
                'roomstay-session': BaseAPI.roomstaySession,
            };
            if (MemberPortalFeature_1.default.isActive()) {
                const Auth = yield (0, AsyncAuth_1.getAuth)();
                try {
                    const cognitoData = yield Auth.currentAuthenticatedUser();
                    const jwtToken = cognitoData.signInUserSession.idToken.jwtToken;
                    baseHeaders['Authorization'] = jwtToken;
                }
                catch (ex) {
                    return;
                }
            }
            return baseHeaders;
        });
    }
    /**
     * Checks if the provided cache object does not need to be reloaded
     * @param obj CacheObject
     */
    isCacheObjectStillValid(obj) {
        if (obj.validUntil.isAfter((0, dayjs_1.default)())) {
            return true;
        }
        return false;
    }
    getApiPath() {
        return config_1.RoomstayGlobalConfig.RoomstayApiUrl;
    }
    formatParams(params, forGet = true) {
        const values = {};
        Object.keys(params).map((p) => {
            let val = params[p];
            if (val === null || val === void 0 ? void 0 : val.format) {
                val = val.format(exports.API_DATE_FORMAT);
            }
            if (val) {
                values[p] = val;
            }
        });
        if (forGet) {
            return new URLSearchParams(values).toString();
        }
        else {
            return values;
        }
    }
}
BaseAPI.roomstaySession = '';
exports.default = BaseAPI;
//# sourceMappingURL=BaseAPI.js.map