/**
 * Created by Gifer on 21.02.2017.
 */

function mcStorage($rootScope) {
    "use strict";

    var callBackFunctions = {};

    var globalOptions = {};

    function sendData(data) {
        $rootScope.$broadcast('sendCMDToElectron', [data.cmd].concat(data.values).concat([
            function (res) {
                if (res && callBackFunctions[res.name] && callBackFunctions[res.name].length && res.name !== "null") {
                    callBackFunctions[res.name].shift()(res.data);
                } else if (data && data.cb) {
                    data.cb(res);
                }
            }
        ]));
    }

    // function getBrowserWindowFromWebContents(remote, contents) {
    //     var topContents = contents;
    //
    //     while (topContents.hostWebContents) {
    //         topContents = topContents.hostWebContents;
    //     }
    //
    //     return remote.BrowserWindow.fromWebContents(topContents);
    // }

    function universalStorage() {
        return {
            load: function (serverID, uin, name, cb) {
                if ($rootScope.isWebClient) {
                    try{
                        if (cb) {
                            cb(webix.storage.local.get(name + uin));
                        } else {
                            return webix.storage.local.get(name + uin);
                        }
                    } catch (e){
                        console.error(e.message);
                    }
                } else {
                    if (!callBackFunctions[name]) {
                        callBackFunctions[name] = [];
                    }

                    callBackFunctions[name].push(cb);

                    sendData({
                        cmd: mcConst._CMD_.ce_storage_get,
                        values: [
                            serverID,
                            uin,
                            name
                        ],
                        cb: cb
                    });
                }
            },

            remove: function (serverID, uin, name, cb) {
                if ($rootScope.isWebClient) {
                    try {
                        if (cb) {
                            cb(webix.storage.local.remove(name + uin));
                        } else {
                            return webix.storage.local.remove(name + uin);
                        }
                    } catch (e){
                        console.error(e.message);
                    }
                } else {
                    sendData({
                        cmd: mcConst._CMD_.ce_storage_remove,
                        values: [
                            serverID,
                            uin,
                            name
                        ],
                        cb: cb
                    });
                }
            },

            save: function (serverID, uin, name, data, cb) {
                if (!data) {
                    this.remove(serverID, uin, name, cb);
                } else
                if ($rootScope.isWebClient) {
                    try {
                        if (cb) {
                            cb(webix.storage.local.put(name + uin, data));
                        } else {
                            return webix.storage.local.put(name + uin, data);
                        }
                    } catch (e){
                        console.error(e.message);
                    }
                } else {
                    sendData({
                        cmd: mcConst._CMD_.ce_storage_save,
                        values: [
                            serverID,
                            uin,
                            name,
                            data
                        ],
                        cb: cb
                    });
                }
            }
        };
    }

    function saveOptions(data, cb) {
        globalOptions = mcService.Marge(globalOptions, data || {});

        if (!mcConst.ServerInfo.ID && !$rootScope.isWebClient){
            console.log("mcConst.ServerInfo.ID : " + mcConst.ServerInfo.ID);
        }

        if ($rootScope.isWebClient) {
            var ID = mcConst.ServerInfo.ID + mcConst.UserInfo.UIN + mcConst.storageOpts.MAIN_OPTIONS;

            try{
                if (cb) {
                    cb(webix.storage.local.put(ID, JSON.stringify(globalOptions)));
                } else {
                    return webix.storage.local.put(ID, JSON.stringify(globalOptions));
                }
            } catch (e){
                console.error(e.message);
            }
        } else {
            sendData({
                cmd: mcConst._CMD_.ce_storage_save,
                values: [
                    mcConst.ServerInfo.ID,
                    mcConst.UserInfo.UIN,
                    mcConst.storageOpts.MAIN_OPTIONS,

                    JSON.stringify(globalOptions)
                ],
                cb: cb
            });
        }
    }

    function loadOptions(cb) {
        if (globalOptions && mcService.isObject(globalOptions) && !mcService.isObjectEmpty(globalOptions)) {
            cb && cb(mcService.Marge({}, globalOptions));
        } else

        if ($rootScope.isWebClient) {
            try {
                globalOptions = webix.storage.local.get(mcConst.ServerInfo.ID + mcConst.UserInfo.UIN + mcConst.storageOpts.MAIN_OPTIONS) || {};
            } catch (e){
                console.error(e.message);
            }

            if (!mcService.isObject(globalOptions) && globalOptions !== "") {
                globalOptions = {};
            }

            if (cb) {
                cb(mcService.Marge({}, globalOptions));
            } else {
                return mcService.Marge({}, globalOptions);
            }
        } else {
            sendData({
                cmd: mcConst._CMD_.ce_storage_get,
                values: [
                    mcConst.ServerInfo.ID,
                    mcConst.UserInfo.UIN,
                    mcConst.storageOpts.MAIN_OPTIONS,
                ],
                cb: function (data) {
                    globalOptions = mcService.StringToObj(data.data) || {};

                    cb && cb(mcService.Marge({}, globalOptions));
                }
            });
        }
    }

    $rootScope.Storage = {
        msgTemplate : universalStorage(),
        saveWndSize : function (cb) {
            if (!$rootScope.isWebClient) {
                require("electron").ipcRenderer.invoke('getWindowWH').then(function (resWH){
                    // console.log("setSizes= " + JSON.stringify(resWH));

                    sendData({
                        cmd: mcConst._CMD_.ce_storage_save,
                        values: [
                            null,
                            null,
                            "WindowSizes",
                            resWH, //[w, h]
                        ],
                        cb: cb
                    });
                });
            }
        },
        historyDialogs: {
            load: function (uin, name, cb) {
                if ($rootScope.isWebClient) {
                    try {
                        if (cb) {
                            cb(webix.storage.local.get(name + uin));
                        } else {
                            return webix.storage.local.get(name + uin);
                        }
                    } catch (e){
                        console.error(e.message);
                    }
                } else {
                    if (!callBackFunctions[name]) {
                        callBackFunctions[name] = [];
                    }

                    callBackFunctions[name].push(cb);

                    sendData({
                        cmd: mcConst._CMD_.ce_history_get_dialogs,
                        values: [],
                        cb: cb
                    });
                }
            },

            remove: function (uin, name, cb) {
                if ($rootScope.isWebClient) {
                    try {
                        if (cb) {
                            cb(webix.storage.local.remove(name + uin));
                        } else {
                            return webix.storage.local.remove(name + uin);
                        }
                    } catch (e){
                        console.error(e.message);
                    }
                } else {
                    sendData({
                        cmd: mcConst._CMD_.ce_history_remove_dialogs,
                        values: [],
                        cb: cb
                    });
                }
            },

            save: function (uin, name, data, cb) {
                if ($rootScope.isWebClient) {
                    try {
                        if (cb) {
                            cb(webix.storage.local.put(name + uin, data));
                        } else {
                            return webix.storage.local.put(name + uin, data);
                        }
                    } catch (e){
                        console.error(e.message);
                    }
                } else {
                    sendData({
                        cmd: mcConst._CMD_.ce_history_set_dialogs,
                        values: [
                            data
                        ],
                        cb: cb
                    });
                }
            }
        },
        dialogs     : universalStorage(),
        contactsTree: universalStorage(),
        statistics  : {
            load: function (serverID, uin, cb) {
                if (!$rootScope.isWebClient) {
                    if (!callBackFunctions[name]) {
                        callBackFunctions[name] = [];
                    }

                    callBackFunctions[name].push(cb);

                    sendData({
                        cmd: mcConst._CMD_.ce_statistics_get,
                        values: [
                            serverID,
                            uin,
                        ],
                        cb: cb
                    });
                }
            },

            save: function (serverID, uin, stat, cb) { // mcConst.ServerInfo.ID
                if (!$rootScope.isWebClient) {
                    sendData({
                        cmd: mcConst._CMD_.ce_statistics_save,
                        values: [
                            serverID,
                            uin,
                            stat
                        ],
                        cb: cb
                    });
                }
            }
        },
        options     : {
            load: loadOptions,
            save: saveOptions
        },
        popularSmiles: universalStorage()
    };

    window.mcStorage = $rootScope.Storage;
}
