(function() {

    var storage = {
        getData: function (url, params) {
            console.log("GET DATA: ",[url, params]);
            return getSchedulerData();
        },
        saveData: function (url, params) {
            var command = parseRequestArguments(params);
            var data = JSON.parse(getSchedulerData());
            console.log("GET DATA SAVE: ",JSON.parse(getSchedulerData()));
            var eventsArray = data.data;

            var updatedEvent = command.event;

            switch (command.action) {
                case "inserted":
                    insertEvent(updatedEvent, eventsArray);
                    break;
                case "updated":
                    updateEvent(updatedEvent, eventsArray);
                    break;
                case "deleted":
                    deleteEvent(updatedEvent, eventsArray);
                    break;
            }

            updateSchedulerData(data);
            return JSON.stringify({action: command.action, tid: updatedEvent.id, sid: updatedEvent.id});
        }
    };

    function insertEvent(event, dataset) {
        var newId = event.id;// leave id unchanged
        dataset.push(event);
        return newId;
    }

    function updateEvent(event, dataset) {
        console.log("UPDATE EVENT: ",[event, dataset])
        var dbEvent;
        for (var i = 0; i < dataset.length; i++) {
            if (dataset[i].id == event.id) {
                dbEvent = dataset[i];
            }
        }

        for (var i in event) {
            dbEvent[i] = event[i];
        }
    }

    function deleteEvent(event, dataset) {
        for (var i = 0; i < dataset.length; i++) {
            if (dataset[i].id == event.id) {
                dataset.splice(i, 1);
                break;
            }
        }
    }

    function updateSchedulerData(data) {
        localStorage.setItem('dhx-scheduler-car-rental-updated', JSON.stringify(data));
    }

    function getSchedulerData() {
        if (!localStorage.getItem('dhx-scheduler-car-rental-updated')) {
            var data = {"data":[{"car":"3","start_date":"2017-09-01 00:00","end_date":"2017-09-09 00:00","text":"New Rent","id":"1506428627671","status":"1","total_cost":"20000"},{"car":"2","start_date":"2017-09-02 00:00","end_date":"2017-09-15 00:00","text":"New Rent","id":"1506513529102","status":"1","total_cost":"55900"},{"car":"1","start_date":"2017-10-02 00:00","end_date":"2017-10-04 00:00","text":"New Rent","id":"1507124045973","status":"1","total_cost":"11200"},{"car":"2","start_date":"2017-10-02 00:00","end_date":"2017-10-05 00:00","text":"New Rent","id":"1507124045974","status":"1","total_cost":"12900"},{"car":"1","start_date":"2017-10-04 00:00","end_date":"2017-10-06 00:00","text":"New Rent","id":"1507124045975","status":"1","total_cost":"11200"}],"collections":{"hour":[{"id":"1","value":"1","label":"00:00"},{"id":"2","value":"2","label":"01:00"},{"id":"3","value":"3","label":"02:00"},{"id":"4","value":"4","label":"03:00"},{"id":"5","value":"5","label":"04:00"},{"id":"6","value":"6","label":"05:00"},{"id":"7","value":"7","label":"06:00"},{"id":"8","value":"8","label":"07:00"},{"id":"9","value":"9","label":"08:00"},{"id":"10","value":"10","label":"09:00"},{"id":"11","value":"11","label":"10:00"},{"id":"12","value":"12","label":"11:00"},{"id":"13","value":"13","label":"12:00"},{"id":"14","value":"14","label":"13:00"},{"id":"15","value":"15","label":"14:00"},{"id":"16","value":"16","label":"15:00"},{"id":"17","value":"17","label":"16:00"},{"id":"18","value":"18","label":"17:00"},{"id":"19","value":"19","label":"18:00"},{"id":"20","value":"20","label":"19:00"},{"id":"21","value":"21","label":"20:00"},{"id":"22","value":"22","label":"21:00"},{"id":"23","value":"23","label":"22:00"},{"id":"24","value":"24","label":"23:00"}],"priceRange":[{"id":"1","value":"1","label":"Budget","minVal":"1000","maxVal":"3000"},{"id":"2","value":"2","label":"Premium","minVal":"3000","maxVal":"5000"},{"id":"3","value":"3","label":"Luxury","minVal":"5000","maxVal":"10000"}],"type":[{"id":"1","value":"1","label":"Single"},{"id":"2","value":"2","label":"Double"},{"id":"3","value":"3","label":"Suite"}],"conditions":[{"id":"1","value":"1","label":"APA - Single Use"},{"id":"2","value":"2","label":"APA - Double Use"},{"id":"3","value":"3","label":"APA - Twin Use"}],"status":[{"id":"1","value":"1","label":"Reservation"},{"id":"2","value":"2","label":"Prepaid"},{"id":"3","value":"3","label":"100% payment"}],"car":[{"id":"1","value":"1","label":"Room 1","price":"5600","link":"http://erp.turismo.cv/web/image/etourism.room/3445/image","type":"3"},{"id":"2","value":"2","label":"Room 2","price":"4300","link":"http://erp.turismo.cv/web/image/etourism.room/3445/image","type":"2"},{"id":"3","value":"3","label":"Room 3","price":"2500","link":"http://erp.turismo.cv/web/image/etourism.room/3445/image","type":"1"}]}};
            localStorage.setItem('dhx-scheduler-car-rental-updated', JSON.stringify(data));
        }

        return localStorage.getItem('dhx-scheduler-car-rental-updated');
    }

    function parseRequestArguments(params) {
        var parts = decodeURIComponent(params).split("&");

        var fieldsMap = {};
        for (var i = 0; i < parts.length; i++) {
            var param = parts[i].split("=");
            fieldsMap[param[0]] = param[1];
        }

        var id = fieldsMap["ids"];

        var action,
            event = {};

        var prefix = id + "_";

        for (var i in fieldsMap) {
            var isEventProperty = i.indexOf(prefix) > -1;
            if (isEventProperty) {
                var fieldName = i.substr(prefix.length);

                if (fieldName == "!nativeeditor_status") {
                    action = fieldsMap[i];
                } else {
                    event[fieldName] = fieldsMap[i];
                }
            }
        }

        return {
            action: action,
            event: event
        };
    }

    var mockAjax = {
        call: function (httpMethod, url, params, callback) {

            var handler = this.router.route(httpMethod, url);
            if (handler) {
                this.executeRequest(httpMethod, handler, url, params, callback);
            } else {
                console.error("no route found " + this.router.urlMask(httpMethod, url));
            }
        },

        executeRequest: function (httpMethod, method, url, params, callback) {
            setTimeout(function () {
                var res = method(url, params);
                console.log(["XHR " + httpMethod.toUpperCase(), url].join(" -> "));
                setTimeout(function () {
                    callback({
                        filePath: url,
                        xmlDoc: {
                            readyState: 4,
                            response: res,
                            responseText: res,
                            status: 200
                        }
                    });
                });
            });
        }
    };

    mockAjax.router = {
        routeMap: {},
        route: function (httpMethod, url) {
            return this.routeMap[this.urlMask(httpMethod, url)];
        },
        urlMask: function (httpMethod, url) {
            return [httpMethod, this._stripUrl(url)].join("->").toLowerCase();
        },
        _stripUrl: function (url) {
            var paramsIndex = url.indexOf("?");
            if (paramsIndex < 0) {
                paramsIndex = url.length;
            }

            return url.substr(0, paramsIndex);
        }
    };

    window.dhtmlxAjax = {
        get: function (url, callback) {
            mockAjax.call("get", url, null, function(res){
                callback(res);
            });
        },
        post: function (url, post, callback) {
            mockAjax.call("post", url, post, function(res){
                callback(res);
            });
        }
    };

    window.dtmlXMLLoaderObject.prototype.loadXML = function (filePath, postMode, postVars) {
        console.log("filePath: ",filePath);
        console.log("postMode: ",postMode);
        console.log("postVars: ",postVars);
        var callback = this.onloadAction;
        mockAjax.call(postMode ? "post" : "get", filePath, postVars, function(res){
            callback(window.dp, null, null, null, res);
        });
    };

    mockAjax.router.routeMap["get->./data.php"] = storage.getData.bind(storage);
    mockAjax.router.routeMap["post->./data.php"] = storage.saveData.bind(storage);

})();