"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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
const config = require("config");
require("isomorphic-fetch");
const { createClient } = require('@commercetools/sdk-client');
const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth');
const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http');
const { createQueueMiddleware } = require('@commercetools/sdk-middleware-queue');
const { createUserAgentMiddleware } = require('@commercetools/sdk-middleware-user-agent');
const { createRequestBuilder, features } = require('@commercetools/api-request-builder');
const { createLoggerMiddleware } = require('@commercetools/sdk-middleware-logger');
const introspection_middleware_1 = require("./introspection-middleware");
const packageInfo = require('../../../package.json');
let __client;
let __services;
function getConfig() {
    if (!config.has('commerceTools')) {
        throw new Error('Project has not been configured yet. Check docs first.');
    }
    return config.get('commerceTools');
}
exports.getConfig = getConfig;
function getClient() {
    if (__client) {
        return __client;
    }
    const sdkConfig = getConfig();
    const middlewares = [
        introspection_middleware_1.createAuthMiddlewareForIntrospectionFlow(sdkConfig),
        createAuthMiddlewareForClientCredentialsFlow({
            host: sdkConfig.authHost,
            projectKey: sdkConfig.projectKey,
            credentials: {
                clientId: sdkConfig.admin.clientId,
                clientSecret: sdkConfig.admin.clientSecret
            }
        }),
        createQueueMiddleware({ concurrency: 10 }),
        createHttpMiddleware({ host: sdkConfig.apiHost }),
        createUserAgentMiddleware({
            libraryName: packageInfo.name,
            libraryVersion: packageInfo.version,
            contactUrl: packageInfo.homepage,
            contactEmail: 'cxcloud@tieto.com'
        })
    ];
    if (sdkConfig.verbose === true) {
        middlewares.push(createLoggerMiddleware());
    }
    __client = createClient({
        middlewares
    });
    return __client;
}
exports.getClient = getClient;
function getServices() {
    if (__services) {
        return __services;
    }
    const sdkConfig = getConfig();
    __services = createRequestBuilder({
        projectKey: sdkConfig.projectKey,
        customServices: {
            login: {
                type: 'login',
                endpoint: '/login',
                features: [features.query]
            },
            activeCart: {
                type: 'active-cart',
                endpoint: '/me/active-cart',
                features: [features.query]
            }
        }
    });
    return __services;
}
exports.getServices = getServices;
function createClientRequest(request) {
    const { token } = request, rest = __rest(request, ["token"]);
    if ('token' in request && typeof token !== 'string') {
        throw new Error('Invalid token provided');
    }
    if (token) {
        return Object.assign({ headers: {
                'X-Custom-OAuth-Token': token
            } }, rest);
    }
    return request;
}
function clientExecute(request) {
    return getClient()
        .execute(createClientRequest(request))
        .then((result) => result.body);
}
exports.clientExecute = clientExecute;
function clientProcess(request) {
    return getClient().process(createClientRequest(request), (payload) => __awaiter(this, void 0, void 0, function* () { return payload.body.results; }));
}
exports.clientProcess = clientProcess;
var methods;
(function (methods) {
    methods["GET"] = "GET";
    methods["POST"] = "POST";
    methods["PATCH"] = "PATCH";
    methods["DELETE"] = "DELETE";
})(methods = exports.methods || (exports.methods = {}));
function authenticatedFormRequest(requestOptions, user = false) {
    const sdkConfig = getConfig();
    const basicAuthCredentials = user
        ? `${sdkConfig.user.clientId}:${sdkConfig.user.clientSecret}`
        : `${sdkConfig.admin.clientId}:${sdkConfig.admin.clientSecret}`;
    const basicAuth = new Buffer(basicAuthCredentials).toString('base64');
    const { uri } = requestOptions, options = __rest(requestOptions, ["uri"]);
    const defaultOptions = {
        headers: {
            Authorization: `Basic ${basicAuth}`,
            'Content-Length': Buffer.byteLength(options.body).toString(),
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    return fetch(new Request(uri, Object.assign({}, defaultOptions, options))).then(res => res.json());
}
exports.authenticatedFormRequest = authenticatedFormRequest;
//# sourceMappingURL=index.js.map