'use strict';

const _ = require('lodash');
const URI = require('urijs');
const url = require('url');

const HTTPSnippet = require('httpsnippet');

module.exports = (endpoint, options, language, mode, languageOptions) => {
    let method = endpoint.options.method.toUpperCase();
    let reqUrl = new URI('http://' + options.host + endpoint.finalUrl);

    let headers = [
        {
            name: 'Accept',
            value: 'application/json',
            comment: 'Formato del resultado',
        },
    ];

    let queryString = [];

    let postData = {
        mimeType: "application/json",
        text: null,
    };

    let postBody = {};

    _.forEach(endpoint.options.request, (field, key) => {
        if(field.source == 'param') {
            let value = field.example || field.defaultValue;
            if(value) {
                reqUrl = reqUrl.replace(new RegExp(':' + key), value);
            }
        }

        if(field.source == 'body') {
            postBody[key] = field.example || null;
        }

        if((!field.source || field.source == 'query') && field.example) {
            queryString.push({
                name: key,
                value: field.example + '',
                comment: field.description,
            });
        }
    });

    if(options.auth_user && options.auth_password) {
        headers.push({
            name: 'Authorization',
            value: 'Basic ' + new Buffer(options.auth_user + ':' + options.auth_password).toString('base64'),
            comment: 'Base64 de "' + options.auth_user + ':' + options.auth_password + '"',
        });
    }

    if(Object.keys(postBody).length > 0) {
        postData.text = JSON.stringify(postBody);

        headers.push({
            name: 'Content-Type',
            value: 'application/json',
            comment: 'Informamos de que el payload del POST es un JSON',
        })
    }

    let har = {
        method: method,
        url: reqUrl.toString(),
        queryString,
        headers,
        postData: postData.text ? postData : undefined,
    };

    if(options.har) {
        har.uriObj = url.parse(reqUrl.toString());

        queryString.forEach(query => {
            reqUrl.addQuery(query.name, query.value);
        });

        har.fullUrl = reqUrl.toString();

        _.defaults(har, {
            cookies: [],
            headersObj: {}
        });

        return har;
    }

    let snippet = new HTTPSnippet(har);
    return snippet.convert(language, mode, languageOptions);
};