const _ = require('lodash');

function getItem(key, data, boundary) {
    boundary = boundary.replace(/^multipart\/form-data; boundary=/, '');

    const type = typeof data === 'string' ? (data.match(/^data:([^;]+);/) || [])[1] : null;
    let item;

    if (type) {
        item = `
            --${boundary}\n
            Content-Disposition: form-data; name="${key}"; filename="${_.uniqueId()}"\n
            Content-Type: ${type}\n\n
            ${new Buffer(data, 'base64').toString()}
        `;
    } else {
        item = `
            --${boundary}\n
            Content-Disposition: form-data; name="${key}"\n
            Content-Type: 'application/octet-stream'\n\n
            ${data}
        `;
    }

    return item;
}

function getData(json) {
    const boundary = _.uniqueId() + _.uniqueId();
    const items = [];

    _.forEach(json, (value, key) => items.push(getItem(key, value, boundary)));

    return {
        body: `${items.join('\n\n')}\n\n--${boundary}--`,
        contentType: `multipart/form-data; boundary=${boundary}`,
    };
}

module.exports = { getItem, getData };
