"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapAgentRequestBuilder = exports.serialize = exports.isErrorResponse = void 0;
var tslib_1 = require("tslib");
var error_1 = require("../error");
var deArrayify_1 = require("./deArrayify");
var i18n_1 = require("../i18n");
var request_builder_1 = require("../request-builder");
var MG_MAPAGENT_ERROR_CODE = 559;
/**
 * Indicates if the given response is an error response
 *
 * @export
 * @param {Response} response
 * @returns {boolean}
 */
function isErrorResponse(response) {
    return !response.ok || response.status === MG_MAPAGENT_ERROR_CODE;
}
exports.isErrorResponse = isErrorResponse;
/**
 * Encodes the given object for a POST submission
 *
 * @export
 * @param {*} data
 * @returns {string}
 */
function serialize(data, uppercase) {
    if (uppercase === void 0) { uppercase = true; }
    return Object.keys(data).map(function (keyName) {
        return encodeURIComponent(uppercase ? keyName.toUpperCase() : keyName) + '=' + encodeURIComponent(data[keyName]);
    }).join('&');
}
exports.serialize = serialize;
/**
 * The mapagent client
 *
 * @export
 * @class MapAgentRequestBuilder
 * @extends {RequestBuilder}
 */
var MapAgentRequestBuilder = /** @class */ (function (_super) {
    tslib_1.__extends(MapAgentRequestBuilder, _super);
    function MapAgentRequestBuilder(agentUri, locale) {
        if (locale === void 0) { locale = i18n_1.DEFAULT_LOCALE; }
        var _this = _super.call(this, agentUri) || this;
        _this.locale = locale;
        return _this;
    }
    MapAgentRequestBuilder.prototype.get = function (url) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var response, json;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, fetch(url, {
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json'
                            },
                            method: "GET"
                        })];
                    case 1:
                        response = _a.sent();
                        if (!isErrorResponse(response)) return [3 /*break*/, 2];
                        throw new error_1.MgError(response.statusText);
                    case 2: return [4 /*yield*/, response.json()];
                    case 3:
                        json = _a.sent();
                        return [2 /*return*/, (0, deArrayify_1.deArrayify)(json)];
                }
            });
        });
    };
    MapAgentRequestBuilder.prototype.post = function (url, data) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var response, json;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!data.format) {
                            data.format = "application/json";
                        }
                        return [4 /*yield*/, fetch(url, {
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                },
                                method: "POST",
                                body: serialize(data) //form
                            })];
                    case 1:
                        response = _a.sent();
                        if (!isErrorResponse(response)) return [3 /*break*/, 2];
                        throw new error_1.MgError(response.statusText);
                    case 2: return [4 /*yield*/, response.json()];
                    case 3:
                        json = _a.sent();
                        return [2 /*return*/, (0, deArrayify_1.deArrayify)(json)];
                }
            });
        });
    };
    MapAgentRequestBuilder.prototype.stringifyGetUrl = function (options) {
        if (!options.version) {
            options.version = "1.0.0";
        }
        if (!options.locale) {
            options.locale = this.locale;
        }
        if (!options.format) {
            options.format = "application/json";
        }
        var url = this.agentUri;
        var bFirst = true;
        for (var key in options) {
            if (bFirst) {
                url += "?".concat(key.toUpperCase(), "=").concat(options[key]);
                bFirst = false;
            }
            else {
                url += "&".concat(key.toUpperCase(), "=").concat(options[key]);
            }
        }
        return url;
    };
    MapAgentRequestBuilder.prototype.createSession = function (username, password) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var url, data, response;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = this.agentUri;
                        data = { operation: "CREATESESSION", version: "1.0.0", USERNAME: username, PASSWORD: password };
                        return [4 /*yield*/, fetch(url, {
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                },
                                method: "POST",
                                body: serialize(data) //form
                            })];
                    case 1:
                        response = _a.sent();
                        if (!isErrorResponse(response)) return [3 /*break*/, 2];
                        throw new error_1.MgError(response.statusText);
                    case 2: return [4 /*yield*/, response.text()];
                    case 3: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    MapAgentRequestBuilder.prototype.getServerSessionTimeout = function (session) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var url, data, response, val;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = this.agentUri;
                        data = { operation: "GETSESSIONTIMEOUT", version: "1.0.0", SESSION: session };
                        return [4 /*yield*/, fetch(url, {
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                },
                                method: "POST",
                                body: serialize(data) //form
                            })];
                    case 1:
                        response = _a.sent();
                        if (!isErrorResponse(response)) return [3 /*break*/, 2];
                        throw new error_1.MgError(response.statusText);
                    case 2: return [4 /*yield*/, response.text()];
                    case 3:
                        val = _a.sent();
                        return [2 /*return*/, parseInt(val, 10)];
                }
            });
        });
    };
    MapAgentRequestBuilder.prototype.getResource = function (resourceId, args) {
        if (args != null) {
            var p1 = { operation: "GETRESOURCECONTENT", resourceId: resourceId };
            var url = this.stringifyGetUrl(tslib_1.__assign(tslib_1.__assign({}, args), p1));
            return this.get(url);
        }
        else {
            var url = this.stringifyGetUrl({ operation: "GETRESOURCE", resourceId: resourceId });
            return this.get(url);
        }
    };
    MapAgentRequestBuilder.prototype.getSiteVersion = function () {
        var p1 = { operation: "GETSITEVERSION", version: "1.0.0", username: "Anonymous" };
        var url = this.stringifyGetUrl(tslib_1.__assign({}, p1));
        return this.get(url);
    };
    MapAgentRequestBuilder.prototype.createRuntimeMap = function (options) {
        var p1 = { operation: "CREATERUNTIMEMAP", version: "3.0.0" };
        var url = this.stringifyGetUrl(tslib_1.__assign(tslib_1.__assign({}, options), p1));
        return this.get(url);
    };
    MapAgentRequestBuilder.prototype.createRuntimeMap_v4 = function (options) {
        var p1 = { operation: "CREATERUNTIMEMAP", version: "4.0.0" };
        var url = this.stringifyGetUrl(tslib_1.__assign(tslib_1.__assign({}, options), p1));
        return this.get(url);
    };
    MapAgentRequestBuilder.prototype.queryMapFeatures = function (options) {
        var p1 = { operation: "QUERYMAPFEATURES", version: "2.6.0" };
        return this.post(this.agentUri, tslib_1.__assign(tslib_1.__assign({}, options), p1));
    };
    MapAgentRequestBuilder.prototype.queryMapFeatures_v4 = function (options) {
        var p1 = { operation: "QUERYMAPFEATURES", version: "4.0.0" };
        return this.post(this.agentUri, tslib_1.__assign(tslib_1.__assign({}, options), p1));
    };
    MapAgentRequestBuilder.prototype.describeRuntimeMap = function (options) {
        var p1 = { operation: "DESCRIBERUNTIMEMAP", version: "3.0.0" };
        var url = this.stringifyGetUrl(tslib_1.__assign(tslib_1.__assign({}, options), p1));
        return this.get(url);
    };
    MapAgentRequestBuilder.prototype.describeRuntimeMap_v4 = function (options) {
        var p1 = { operation: "DESCRIBERUNTIMEMAP", version: "4.0.0" };
        var url = this.stringifyGetUrl(tslib_1.__assign(tslib_1.__assign({}, options), p1));
        return this.get(url);
    };
    MapAgentRequestBuilder.prototype.getTileTemplateUrl = function (resourceId, groupName, xPlaceholder, yPlaceholder, zPlaceholder, isXYZ) {
        if (isXYZ)
            return "".concat(this.agentUri, "?OPERATION=GETTILEIMAGE&VERSION=1.2.0&USERNAME=Anonymous&MAPDEFINITION=").concat(resourceId, "&BASEMAPLAYERGROUPNAME=").concat(groupName, "&TILECOL=").concat(yPlaceholder, "&TILEROW=").concat(xPlaceholder, "&SCALEINDEX=").concat(zPlaceholder);
        else
            return "".concat(this.agentUri, "?OPERATION=GETTILEIMAGE&VERSION=1.2.0&USERNAME=Anonymous&MAPDEFINITION=").concat(resourceId, "&BASEMAPLAYERGROUPNAME=").concat(groupName, "&TILECOL=").concat(xPlaceholder, "&TILEROW=").concat(yPlaceholder, "&SCALEINDEX=").concat(zPlaceholder);
    };
    return MapAgentRequestBuilder;
}(request_builder_1.RequestBuilder));
exports.MapAgentRequestBuilder = MapAgentRequestBuilder;
//# sourceMappingURL=mapagent.js.map