"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());
    });
};
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");
/**
 * Convenience function that
 * @param id
 * @param args
 * @param onResult
 * @param onError
 */
function callService(id, args, onResult, onError) {
    return __awaiter(this, void 0, void 0, function* () {
        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);
            onError(`could not find service with id: ${id}`);
            return;
        }
        const urlPath = iso_libs_1.getBasename() !== undefined ? path.join(iso_libs_1.getBasename(), serviceComponent.path) : serviceComponent.path;
        console.log("urlPath: ", urlPath);
        /*
    
        const hostname = process.env.DOMAIN_URL;
    
        console.log(`hostname ${hostname}`);
        */
        // apparently, the fetch does not require the hostname...why?
        yield fetch(`${urlPath}`, {
            method: serviceComponent.method,
            body: JSON.stringify(args),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json",
                "Accept-Charset": "utf-8"
            }
        }).then(result => {
            console.log("post result: ", result);
            onResult(result);
        }).catch(error => {
            console.error("post-error: ", error);
            onError(error);
        });
        //
    });
}
exports.callService = callService;
//# sourceMappingURL=service-libs.js.map