/**
 * Created by linwang5 2014/9/30.
 * 用于监管用戶并上传log，集成了logCenterSDK
 */

define(function(require,exports){
    var TrackService = window.require('./node_modules/logcenter/trackClient').TrackService;
    var TrackParam = window.require('./node_modules/logcenter/paramType').TrackParam;
    var uuid = window.require('./node_modules/logcenter/lib/uuid');
    var urlCheck = require('editor/assert/js/addon/urlCheck');
    var AppContext = require('share/assert/js/appcontext').AppContext;
    var fs = window.require('fs');
    var logUtil = require('editor/assert/js/utils/logUtil').logUtil;

    var LOG_CONFIG={host:"172.16.79.22",port:8280,path:"/logcenter_alpha"};
    var LOG_CENTER_DAT_FILEPATH = AppContext.getBinPath() + '/logCenter.dat';

    logUtil.TAG = 'LogManager.js';

    var LogManager = {
        sessionList: new Array(),
        client: new TrackService(),
        paramFactor: new TrackParam(),
        config: LOG_CONFIG,
//        isOnline:false,

        //添加进入模块监控记录
        setAddEntryTrack: function (module) {
            logUtil.log('setAddEntryTrack:'+module);
            LogManager.client.AddEntryTrack(module);
        },

        //添加退出模块监控记录
        setAddQuiteTrack: function (module) {
            logUtil.log('setAddQuiteTrack:'+module);
            LogManager.client.AddQuiteTrack(module);
        },

        //添加频度统计监控记录
        setAddTiggerTrack: function (module, action, params, result) {
            logUtil.log('setAddTiggerTrack: module='+module+',action='+action+",params="+params);

            LogManager.client.AddTiggerTrack(module, action, params, result)
        },

        manageConfigBaseInfo: function (args) {
            //对应paraConfig
            LogManager.paramFactor.ConfigBaseInfo(args);
        },

        //上传监控记录
        //上传成功后会清空以前的添加的用户记录，失败则不会清空
        upLoadLog: function () {
            console.log("upload log");
            this.client.UploadTrackLog(function (err, res) {
                console.log(res);
            });

        },

        //初始化session
        initConfig: function () {
            urlCheck.pingBaidu().done(function(ret) {
                logUtil.log('isOnline:'+ret);
//                LogManager.isOnline = ret;

                LogManager.client.Init(LogManager.config, function (err, res) {
                    logUtil.log(res);
                });
            });
        },

        statisticsMoudleTime: function (moduleId, actionName, extraParam) {
            var dt = new Date();
            dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
            var paramConfig = {
                "product": "jhkj",
                "app": "jhkj",
                "user_id": '',
                "timestamp": dt.toISOString(),
                "session_id": LogManager.sessionManager(moduleId, actionName)
            };

            logUtil.log('statisticsMoudleTime paramConfig:'+JSON.stringify(paramConfig));

            // 离线时存放本地
            urlCheck.pingBaidu().done(function(ret) {
//                console.log('online ---- '+ret);
//                LogManager.isOnline = ret;
                if (ret == false) {
                    console.log("save log to local");
                    LogManager.saveLogToLocal(paramConfig, actionName, moduleId,extraParam);
                    return;
                }
                else{
                    // 有监管日志立即上传
                    LogManager.manageConfigBaseInfo(paramConfig);
                    if (actionName == "entry") {
                        LogManager.setAddEntryTrack(moduleId);
                    } else if (actionName== "quit") {
                        LogManager.setAddQuiteTrack(moduleId);
                    } else {
                        LogManager.setAddTiggerTrack(moduleId, actionName, extraParam, "");
                    }
                    LogManager.upLoadLog();
                    LogManager.upLocalLog();
                }
            });
        },
        saveLogToLocal: function (paramConfig, actionName, moduleId,extraParam) {
            var LocalLogItem = {
                param: paramConfig,
                action: actionName,
                id: moduleId,
                extra:extraParam
            };
            var infoPath = LOG_CENTER_DAT_FILEPATH;
            infoPath = infoPath.replace(/\\/gi,'/');
            logUtil.log('local log path:'+infoPath);
            try {
                if(!fs.existsSync(infoPath)) {
                    fs.writeFileSync(infoPath, '[]');
                }

                var fileContent = fs.readFileSync(infoPath);
                //logUtil.log(fileContent);
                var LocalLog = JSON.parse(fileContent) || [];
                LocalLog.push(LocalLogItem);
                logUtil.log('save to local:'+JSON.stringify(LocalLog));
                fs.writeFileSync(infoPath, JSON.stringify(LocalLog));
            } catch (e) {
                console.error(e.message);
            }
        },
        upLocalLog: function () {
//            urlCheck.pingBaidu().done(function(ret) {
//                LogManager.isOnline = ret;
//                if (ret == false) {
//                    return;
//                }
//                else{
            console.log("upload local log");
                    var infoPath = LOG_CENTER_DAT_FILEPATH;
                    infoPath = infoPath.replace(/\\/gi,'/');

                    logUtil.log('local log path:'+infoPath);
                    try {
                        if(!fs.existsSync(infoPath)) {
                            fs.writeFileSync(infoPath, '[]');
                        }

                        var LocalLog = JSON.parse(fs.readFileSync(infoPath)) || [];
                        if (LocalLog.length == 0) {
                            console.log('local log is empty, return.');
                            return;
                        }

                        var tempLocalLog = [];
                        fs.writeFileSync(infoPath, JSON.stringify(tempLocalLog));
                        for (var i in LocalLog) {
                            LogManager.manageConfigBaseInfo(LocalLog[i].param);
                            if (LocalLog[i].action == "entry") {
                                LogManager.setAddEntryTrack(LocalLog[i].id);
                            } else if (LocalLog[i].action == "quit") {
                                LogManager.setAddQuiteTrack(LocalLog[i].id);
                            } else {
                                LogManager.setAddTiggerTrack(LocalLog[i].id, LocalLog[i].action, LocalLog[i].extra, "");
                            }
                        }
                        LogManager.upLoadLog();
                    } catch (e) {
                        console.error(e.message);
                    }
//                }
//            });
        },
        sessionManager: function (id, action) {
            if(action=="entry"||action=="quit"){
                for (var i in LogManager.sessionList) {
                    if (LogManager.sessionList[i].appId == id) {
                        var result = LogManager.sessionList[i].sessionId;
                        if (action == "quit") {
                            LogManager.sessionList.pop(LogManager.sessionList[i]);
                        }
                        return result;
                    }
                }
                var result = {
                    appId: id,
                    sessionId: ''
                };
                uuid.create();
                result.sessionId = uuid.create().toString();
                LogManager.sessionList.push(result);
                return result.sessionId;
            }
            uuid.create();
            return uuid.create().toString();
        }
    };

    (function() {
        setTimeout(function(){
            console.log('init log service......');
            LogManager.initConfig();
        },2000);
    })();

    exports.LogManager = LogManager;
});