"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
const CurlOption_1 = require("./generated/CurlOption");
const Curl_1 = require("./Curl");
// This is basically http.METHODS
const methods = [
    'acl',
    'bind',
    'checkout',
    'connect',
    'copy',
    'delete',
    'get',
    'head',
    'link',
    'lock',
    'm-search',
    'merge',
    'mkactivity',
    'mkcalendar',
    'mkcol',
    'move',
    'notify',
    'options',
    'patch',
    'post',
    'propfind',
    'proppatch',
    'purge',
    'put',
    'rebind',
    'report',
    'search',
    'source',
    'subscribe',
    'trace',
    'unbind',
    'unlink',
    'unlock',
    'unsubscribe',
];
const create = () => {
    function curly(url, options = {}) {
        const curlHandle = new Curl_1.Curl();
        curlHandle.setOpt('URL', url);
        for (const key of Object.keys(options)) {
            const keyTyped = key;
            const optionName = keyTyped in CurlOption_1.CurlOptionCamelCaseMap
                ? CurlOption_1.CurlOptionCamelCaseMap[keyTyped]
                : keyTyped;
            // @ts-ignore @TODO Try to type this
            curlHandle.setOpt(optionName, options[key]);
        }
        return new Promise((resolve, reject) => {
            try {
                curlHandle.on('end', (statusCode, data, headers) => {
                    curlHandle.close();
                    resolve({
                        statusCode: statusCode,
                        data: data,
                        headers: headers,
                    });
                });
                curlHandle.on('error', (error, errorCode) => {
                    curlHandle.close();
                    // @ts-ignore
                    error.code = errorCode;
                    reject(error);
                });
                curlHandle.perform();
            }
            catch (error) {
                curlHandle.close();
                reject(error);
            }
        });
    }
    curly.create = create;
    for (const httpMethod of methods) {
        // @ts-ignore
        curly[httpMethod] =
            httpMethod === 'get'
                ? curly
                : (url, options = {}) => curly(url, {
                    customRequest: httpMethod,
                    ...options,
                });
    }
    // @ts-ignore
    return curly;
};
/**
 * Curly function
 *
 * @public
 */
exports.curly = create();
//# sourceMappingURL=curly.js.map