"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EwizardClient = void 0;
const semver = require("semver");
const url_1 = require("url");
const Config_1 = require("../../modules/Config");
const I18n_1 = require("../../modules/I18n");
const Logger_1 = require("../../modules/Logger");
const Request_1 = require("../../modules/Request");
const SecureRequest_1 = require("../../modules/SecureRequest");
const WizError_1 = require("../../modules/WizError");
const routes_1 = require("./routes");
const ewizardService_types_1 = require("../../interfaces/ewizardService.types");
const request = new Request_1.default();
class EwizardClient {
    constructor(url, apiUrl, tokenHandler, keyCloakClient) {
        this.url = url;
        this.apiUrl = apiUrl;
        this.tokenHandler = tokenHandler;
        this.keyCloakClient = keyCloakClient;
        this.request = new SecureRequest_1.default(this.tokenHandler, this.keyCloakClient);
    }
    getConfig() {
        return getAuthUrl(this.url)
            .then(authUrl => getConfigByAuth(this.url, authUrl))
            .catch(err => this.handleError(err, this.url));
    }
    getEwizardVersion(url = this.apiUrl) {
        return request.get(url + routes_1.default.ewizardVersion)
            .then(validateVersion(url))
            .catch(err => this.handleError(err, url));
    }
    getComponentLibrary() {
        return this.get(routes_1.default.componentLibrary);
    }
    getUser() {
        return this.get(routes_1.default.user);
    }
    getGraylog() {
        return this.get(routes_1.default.graylog);
    }
    getNpmRegistry({ action, repositoryType }) {
        const route = routes_1.default.npmRegistry
            .replace('{action}', action)
            .replace('{repositoryType}', repositoryType);
        const requestUrl = this.apiUrl + route;
        return this.request.get(requestUrl)
            .catch((err) => {
            if (err.code === 'FORBIDDEN') {
                switch (action) {
                    case ewizardService_types_1.ActionType.Install:
                        Logger_1.default.info(I18n_1.default.info('NO_INSTALL_PERMISSION'));
                        return { registry: '', token: '' };
                    case ewizardService_types_1.ActionType.Publish:
                        throw new WizError_1.WizError(I18n_1.default.error('NO_PUBLISH_PERMISSIONS', repositoryType));
                    default:
                        throw new WizError_1.WizError('Invalid ActionType');
                }
            }
            this.handleError(err, requestUrl);
        });
    }
    get(route) {
        const requestUrl = this.apiUrl + route;
        return this.request.get(requestUrl)
            .catch((err) => this.handleError(err, requestUrl));
    }
    post(route, options) {
        const requestUrl = this.apiUrl + route;
        return this.request.post(requestUrl, options)
            .catch((err) => this.handleError(err));
    }
    handleError(err, url) {
        switch (err.code) {
            case 'INVALID_URL':
            case 'NOT_FOUND':
                throw new WizError_1.WizError('INVALID_INSTANCE', url);
            case 'SERVER_ERROR':
            case 'SERVER_UNAVAILABLE':
                throw new WizError_1.WizError('EWIZARD_UNAVAILABLE', url);
        }
        throw err;
    }
}
exports.EwizardClient = EwizardClient;
function validateVersion(url) {
    return (version) => {
        const valid = semver.valid(version);
        if (!valid) {
            throw new WizError_1.WizError('INVALID_INSTANCE', url);
        }
        return version;
    };
}
function getAuthUrl(ewizardUrl) {
    return request.get(ewizardUrl + '/endpoints.json')
        .then(getAuthorization);
}
function getConfigByAuth(ewizardUrl, authUrl) {
    return Config_1.Config.get()
        .then(config => {
        const url = new url_1.URL(ewizardUrl);
        const realm = url.hostname.split('.')[0];
        return Object.assign(Object.assign({}, config.defaultAuthServer), { url: authUrl, realm });
    });
}
function getAuthorization(endpoints) {
    try {
        return JSON.parse(endpoints).authorization;
    }
    catch (_a) {
        throw new WizError_1.WizError('GET_AUTH_URL_ERROR');
    }
}
//# sourceMappingURL=index.js.map