import { CodeBuilder } from '../../helpers/code-builder.js';
import { buildUrlExpression, printUrlVariablesDeclarations } from '../../helpers/code-helpers.js';
import { Lang } from '../../helpers/constants.js';
import { HTTPSnippet } from '../../index.js';
import { normalizeMimeType } from '../../../../utils.js';
import { MediaTypes } from '../../../../../constants.js';
import { postDataToRListBody, objectToRString } from './utils.js';
const indent = 1;
const handler = function (source, originalOptions, { target, client }) {
    const options = Object.assign({ indent: '  ', showBoilerplate: true, printBody: true }, originalOptions);
    const code = new CodeBuilder({
        indentation: options.indent,
        variablesPrefix: options.variablesPrefix,
        lang: Lang.R,
    });
    const reqMethod = source.method.toUpperCase();
    const securityOAuth2ExtraCalls = source.securityOAuth2ExtraCalls?.[0];
    if (options.showBoilerplate) {
        code.push('library(httr)').blank();
    }
    if (securityOAuth2ExtraCalls) {
        const prefix = 'oauth2_';
        const oAuth2PrefixCode = new HTTPSnippet(securityOAuth2ExtraCalls).convert(target, client, {
            ...options,
            variablesPrefix: prefix,
            showBoilerplate: false,
        });
        const responseVariable = `${prefix}data_req`;
        code
            .push(oAuth2PrefixCode)
            .push(`access_token = content(${responseVariable}, "parsed")$access_token`)
            .blank();
        source.allHeaders.Authorization = `paste("Bearer", access_token)`;
    }
    // Print all the post data
    let encode;
    let bodyVariableName = '';
    if (source?.postData) {
        switch (normalizeMimeType(source?.postData?.mimeType)) {
            case MediaTypes.URL_ENCODED: {
                encode = 'form';
                bodyVariableName = code.var('body');
                const stringifiedPostData = postDataToRListBody(source.postData.params, options);
                code.push(`${bodyVariableName} <- list(${stringifiedPostData})`).blank();
                break;
            }
            case MediaTypes.JSON: {
                encode = 'json';
                bodyVariableName = code.var('body');
                const stringifiedPostData = objectToRString(source.postData.jsonObj, options);
                code.push(`${bodyVariableName} = '${stringifiedPostData}'`).blank();
                break;
            }
            case MediaTypes.MULTIPART: {
                encode = 'multipart';
                bodyVariableName = code.var('body');
                const stringifiedPostData = postDataToRListBody(source.postData.params, options);
                code.push(`${bodyVariableName} <- list(${stringifiedPostData})`).blank();
                break;
            }
            default:
                if (source.postData?.text) {
                    bodyVariableName = code.var('body');
                    encode = 'raw';
                    code.push(`${bodyVariableName} = ${objectToRString(source.postData?.text)}`).blank();
                }
        }
    }
    // print option parameter
    printUrlVariablesDeclarations(source, code);
    if (Object.keys({ ...source.pathParameters, ...source.serverVariables }).length) {
        code
            .blank()
            .push('# create you own operator')
            .push('"%&%" <- function(x, y)paste0(x,y)')
            .blank();
    }
    const url = buildUrlExpression(source, code);
    code.push(`url = ${url}`).blank();
    // make request
    const requestVariableName = code.var('data_req');
    code.push(`${requestVariableName} <- ${reqMethod}(`);
    code.push(indent, 'url,');
    if (source.basicAuth) {
        const { username, password } = source.basicAuth;
        code.push(indent, `authenticate("${username}", "${password}")`);
    }
    if (Object.keys(source.allHeaders).length) {
        const headersCode = `${Object.keys(source.allHeaders)
            .map((key) => `"${key}" = ${source.allHeaders[key].startsWith('paste')
            ? source.allHeaders[key]
            : `"${source.allHeaders[key]}"`}`)
            .join(', ')}`;
        if (headersCode) {
            code.push(indent, `add_headers(${headersCode}),`);
        }
    }
    if (bodyVariableName) {
        code.push(indent, `body = ${bodyVariableName},`);
        code.push(indent, `encode = "${encode}",`);
    }
    code.push(indent, 'verbose()');
    code.push(')');
    // Print code that makes response
    if (options.printBody) {
        code.blank().push(`content(${requestVariableName}${encode === 'raw' ? ', "text"' : ''})`);
    }
    return code.join();
};
export default handler;
//# sourceMappingURL=httr.js.map