"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 });
const loader_1 = require("../libs/loader");
const types_1 = __importDefault(require("../types"));
const iso_libs_1 = require("../libs/iso-libs");
const exenv_1 = __importDefault(require("exenv"));
/**
 * Convenience function that
 * @param id
 * @param args
 * @param onResult
 * @param onError
 */
function callService(id, args, onResult, onError, config, isOffline = false) {
    return __awaiter(this, void 0, void 0, function* () {
        //console.log("callService: ", id, args);
        const path = require("path");
        // load the IsomorphicComponent
        // we must load it directly from the module here, to enable the aliad of the config_file_path
        const isoConfig = config == undefined ?
            loader_1.loadConfigurationFromModule(require('__CONFIG_FILE_PATH__'), loader_1.INFRASTRUCTURE_MODES.RUNTIME) : config;
        // let's extract it from the root configuration
        const serviceComponent = loader_1.extractObject(isoConfig, types_1.default.INFRASTRUCTURE_TYPE_COMPONENT, id);
        if (!serviceComponent) {
            console.error("could not find service with id: ", id);
            onError(`could not find service with id: ${id}`);
            return;
        }
        const basename = iso_libs_1.getBasename();
        /*console.log("basename: ", basename);
    
        console.log("isOffline: ", isOffline);
        console.log("Domain Url: ", process.env.DOMAIN_URL);*/
        // only if were at the server, (ISO-only!) we need to add the server name
        const urlPath = !exenv_1.default.canUseDOM ? (isOffline ? "http://localhost:3000" + serviceComponent.path : process.env.DOMAIN_URL.toString() + serviceComponent.path) : (basename !== undefined ? (basename.startsWith("http") ?
            basename + serviceComponent.path :
            path.join(basename, serviceComponent.path)) : serviceComponent.path);
        //console.log("urlPath: ", urlPath);
        const params = {
            method: serviceComponent.method,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json",
                "Accept-Charset": "utf-8"
            }
        };
        // apparently, the fetch does not require the hostname...why?
        yield fetch(serviceComponent.method === "POST" ? urlPath : urlPath.concat(Object.keys(args).reduce((result, key, index) => result.concat(index > 0 ? "&" : "?", key, "=", args[key]), "")), serviceComponent.method === "POST" ? Object.assign({
            body: JSON.stringify(args)
        }, params) : params).then(result => {
            //console.log("post result: ", result);
            onResult(result);
        }).catch(error => {
            //console.error("post-error: ", error);
            onError(error);
        });
        //console.log("callService done")
    });
}
exports.callService = callService;
function getServiceUrl(id, args) {
    const path = require("path");
    // load the IsomorphicComponent
    // we must load it directly from the module here, to enable the aliad of the config_file_path
    const isoConfig = loader_1.loadConfigurationFromModule(require('__CONFIG_FILE_PATH__'), loader_1.INFRASTRUCTURE_MODES.RUNTIME);
    //console.log("isoConfig: ", isoConfig)
    // let's extract it from the root configuration
    const serviceComponent = loader_1.extractObject(isoConfig, types_1.default.INFRASTRUCTURE_TYPE_COMPONENT, id);
    if (!serviceComponent) {
        console.error("could not find service with id: ", id);
        return undefined;
    }
    const servicePath = Object.keys(args).reduce((res, key) => {
        return res.replace(new RegExp(`:${key}`), args[key]);
    }, serviceComponent.path);
    return iso_libs_1.getBasename() !== undefined ? path.join(iso_libs_1.getBasename(), servicePath) : servicePath;
}
exports.getServiceUrl = getServiceUrl;
//# sourceMappingURL=service-libs.js.map