'use strict';
/**
 * ApiRequest: thư viện hỗ trợ tạo request lên server api
 */

var config = require('../../config/config'),
    request = require('request');

exports.post = function(apiName, param, callback) {
    if (typeof(param) === 'function') {
        callback = param;
        param = {};
    }
    var options = {
        method: 'POST',
        uri: config.api_host + apiName,
        json: param
    };
    if (param && param.token) {
        options['auth'] = {
            'bearer': param.token
        };
    }
    // request ato API Host
    request(options, function(err, httpResponse, body) {
        if (err) {
            callback(err, body);
        } else if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
            callback(err, body);
        } else {
            callback(body);
        }
    });
};

exports.get = function(apiName, param, callback) {
    if (typeof(param) === 'function') {
        callback = param;
        param = {};
    }
    var url = config.api_host + apiName;
    for (var k in param) {
        url += k + '=' + param[k] + '&';
    }
    var options = {
        method: 'GET',
        uri: url,
        json: true
    };
    if (param && param.token) {
        options['auth'] = {
            'bearer': param.token
        };
    }
    // request ato API Host
    request(options, function(err, httpResponse, body) {
        if (err) {
            callback(err, body);
        } else if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
            callback(err, body);
        } else {
            callback(body);
        }
    });
};
