"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicProxy_1 = require("./dynamicProxy");
class UI {
    constructor() {
        var storedStr = localStorage.getItem('methodusTestParams') || '{}';
        this.store = JSON.parse(storedStr);
        var selected = document.querySelectorAll('.store');
        selected.forEach((param) => {
            const cacheValue = this.store[param.name || param.id];
            if (cacheValue !== undefined && cacheValue !== null) {
                param.value = cacheValue;
            }
        });
        this.client = new dynamicProxy_1.Proxy();
    }
    renderJsonResponse(element, data, options) {
        options = options || { collapsed: true };
        $(element).jsonViewer(data, options);
    }
    cacheParams() {
        var selected = document.querySelectorAll('.store');
        const storedStr = localStorage.getItem('methodusTestParams') || '{}';
        this.store = JSON.parse(storedStr);
        selected.forEach((param) => {
            this.store[param.name || param.id] = param.value;
        });
        localStorage.setItem('methodusTestParams', JSON.stringify(this.store));
        return true;
    }
    updateParam() {
        //document.getElementById('TestForm').action = url;
        // execute();
        //build the request url (params + query)
        var selected = document.querySelectorAll('.param');
        const testForm = document.getElementById('TestForm');
        const params = [];
        if (testForm) {
            var url = testForm.getAttribute('xaction');
            const method = testForm.getAttribute('method');
            if (selected && url) {
                selected.forEach(function (param) {
                    params.push({ id: param.id, value: param.value });
                });
            }
            var selectedQuery = document.querySelectorAll('.query');
            let queryString = [];
            selectedQuery.forEach(function (param) {
                if (param.value) {
                    queryString.push(`${param.id}=${param.value}`);
                }
            });
            const RequestUrl = document.getElementById('RequestUrl');
            if (RequestUrl) {
                let finalUrl = url;
                params.forEach((param) => {
                    finalUrl = finalUrl.replace(`:${param.id}`, param.value);
                });
                RequestUrl.innerHTML = finalUrl;
            }
            //add body
            const body = {};
            let selectedBody = document.querySelectorAll('.body');
            selectedBody.forEach(function (param) {
                if (param.name) {
                    body[param.name] = param.value;
                }
                else {
                    try {
                        const str = param.value;
                        const obj = JSON.parse(str);
                        Object.assign(body, obj);
                    }
                    catch (error) {
                        console.error(param.value, 'not a json object');
                    }
                }
            });
            let headers = {};
            if (this.store['att_security_context']) {
                headers = {
                    "dev-iv-user": `"${this.store['att_security_context']}"`,
                    "iv-user": `"${this.store['att_security_context']}"`
                };
            }
            this.client.prepare(url, method, params, body, queryString, headers);
        }
    }
    jsonHandler(json) {
        return __awaiter(this, void 0, void 0, function* () {
            $('#HtmlPane').hide();
            $('#JsonPane').show();
            $('#JsonPane').jsonViewer(json, { collapsed: false });
        });
    }
    htmlHandler(html) {
        return __awaiter(this, void 0, void 0, function* () {
            $('#JsonPane').hide();
            $('#HtmlPane').html(html).show();
        });
    }
    responseHandler(response) {
        return __awaiter(this, void 0, void 0, function* () {
            const responseHeaders = document.getElementById('ResponseHeaders');
            if (responseHeaders) {
                responseHeaders.innerHTML = JSON.stringify({ url: response.url });
            }
            const RequestUrl = document.getElementById('RequestUrl');
            if (RequestUrl) {
                RequestUrl.innerHTML = response.url;
            }
            if (response.status === 200) {
                $('#ResultStatusOK').show();
                $('#ResultStatusBAD').hide();
            }
            else {
                $('#ResultStatusOK').hide();
                $('#ResultStatusBAD').show();
            }
            $('#StatusCode').html(response.status);
        });
    }
    execute() {
        return __awaiter(this, void 0, void 0, function* () {
            this.cacheParams();
            this.updateParam();
            yield this.client.execute(this.responseHandler, this.jsonHandler, this.htmlHandler);
        });
    }
}
exports.UI = UI;
window.ui = new UI();
