define(["bluebird", "config"], function() {

    var xhrService = {};
    var Promise = require("bluebird");
    var config = require("config");

    // global
    var XMLHttpRequest = window.XMLHttpRequest; // require('xhr2');

    xhrService.xhr = function() {
        return new XMLHttpRequest();
    };

    var formUrlEncode = function(data) {
        var str = [];
        if (data) {
            Object.keys(data).forEach(function(key) {
                str.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
            });
        }
        return str.join("&");
    };

    xhrService.customAjax = new function() {

        var self = this;

        if (config.isDesktop) {
            self.ajax = $.ajax.bind($);
        } else {
            self.ajax = function(param1, param2) {

                if (typeof arguments[0] === 'object') {
                    settings = arguments[0];
                }

                if (typeof arguments[1] === 'object') {
                    settings = arguments[1];
                }

                if (typeof arguments[0] === 'string') {
                    settings.url = arguments[0];
                }

                var defaultUrl = 'http://127.0.0.1:9500';
                var currentUrl = window.location.origin;
                if (currentUrl.toLowerCase() === 'file://') {
                    currentUrl = defaultUrl;
                }

                // create clone of settings, because else the url on both objects is overwritten on the next line.
                var newSettings = $.extend({}, settings);
                newSettings.url = currentUrl + '/api/data/ajax';
                newSettings.method = 'POST';
                newSettings.data = JSON.stringify(settings);
                newSettings.contentType = 'application/json'
                newSettings.converters = {
                    "* text": window.String,
                    "text html": true,
                    "text json": jQuery.parseJSON,
                    "text script": jQuery.parseJSON,
                    "text xml": jQuery.parseXML
                };


                return $.ajax(newSettings).error(function(xhr, err) {
                    console.log(err, newSettings.url, xhr.getAllResponseHeaders());
                });
            }
        }

    }

    xhrService.request = function(settings) {

        settings = settings || {};
        return new Promise(function(resolve, reject) {
            var method = settings.method || "GET";
            var url = settings.url || "";
            var data = settings.data;
            var contentType = settings.contentType || "x-www-form-urlencoded";
            var headers = settings.headers || [];
            var responseType = settings.responseType || "text";
            var postData = null;

            if (typeof(data) !== "string") {
                if (contentType === "x-www-form-urlencoded") {
                    postData = formUrlEncode(data);
                } else if (contentType === "json") {
                    postData = JSON.stringify(data);
                }
            }

            var xhr = xhrService.xhr();
            if (!xhr) {
                reject("Error: could not create a XMLHttpRequest");
                return;
            }

            xhr.open(method, url, true);

            if (headers) {
                Object.keys(headers).forEach(function(key) {
                    xhr.setRequestHeader(key, headers[key]);
                });
            }

            //xhr.timeout = 30000; // 30 seconds

            xhr.addEventListener("error", function(event) {
                reject("Error: network error");
            });
            xhr.addEventListener("timeout", function(event) {
                reject("Error: timeout error");
            });

            xhr.responseType = responseType;
            xhr.addEventListener("load", function(event) {
                if (xhr.status >= 400) {
                    reject(xhr);
                } else {
                    resolve(xhr);
                }
            }, false);
            xhr.send(postData);
        });
    };

    return xhrService;
});
