
crmApp.factory('ActivitySessionService', function (localStorageService, ActivitySI) {

    var service = {};
    var actSession = localStorageService.get('ActSession');

    if (!actSession) {
        actSession = [];
        localStorageService.set('ActSession', actSession);
    }

    var init = function () {
        //after actSession assigned latest fr LS

        //update unsaved activity sessions
        savePendingSessions();

        //delete expired acitivity sessions
        deleteExpiredSessions();

        //at page proceed to bind to scope
    };

    var refresh = function () {

        //delete expired acitivity sessions
        deleteExpiredSessions();
    }

    var getActSessionBySID = function (_sessionKey) {
        var o = null;
        var index = getSessionIndexbySID(_sessionKey);

        if (index != -1) {
            o = actSession[index];
        }

        return o;
    }

    var getValidActSessionBySID = function (_sessionKey, _dtNow) {
        var o = null;
        var index = getSessionIndexbySID(_sessionKey);

        if (index != -1) {
            o = actSession[index].ExpiryDate >= _dtNow ? actSession[index] : null;
        }

        return o;
    }

    var getSessionIndexbySID = function (_sessionKey) {

        for (var i = 0; i < actSession.length; i++) {
            if (actSession[i] && actSession[i].SID == _sessionKey) {
                return i;
            }
        }

        return -1;
    };

    var savePendingSessions = function () {

        for (var i = 0; i < actSession.length; i++) {
            var objActSession = actSession[i];
            if (objActSession && objActSession.AID.length >= 2 && objActSession.LastSavedIndex < (actSession[i].AID.length - 1)) {

                var vmActSession = [];

                for (var j = objActSession.LastSavedIndex + 1; j < actSession[i].AID.length; j++) {
                    vmActSession.push({ SessionKey: objActSession.SID, ActivityID: objActSession.AID[j] })
                }
                console.log("save skey");
                console.log("vmActSession");
                callUpdateAPI(objActSession, vmActSession);
            }
        }
    };

    var callUpdateAPI = function (obj, vm) {

        ActivitySI.saveActSession(vm).then(function (r) {
            if (r.status == 200) {
                //var n = actSession.indexOf(obj);
                //if (n != -1)
                var o = getActSessionBySID(obj.SID);
                !o || (o.LastSavedIndex = obj.AID.length - 1);
                //obj.LastSavedIndex = obj.AID.length - 1;
                console.log(actSession);
            }
        });
    };

    var deleteExpiredSessions = function () {
        var dtNow = new Date();

        for (var i = actSession.length - 1; i >= 0; i--) {
            if (actSession[i] && (actSession[i].ExpiryDate < dtNow || actSession[i].AID[0] === null)) {
                actSession.splice(i, 1);
            }
        }
        console.log("After Delete skey: actSession");
        console.log(actSession);
    };

    service = {
        bind: function (scope) {
            console.log("B4 bind, the scope.ActSession: ");
            console.log(scope.ActSession);
            localStorageService.bind(scope, 'ActSession');
            console.log("Aft bind, the scope.ActSession: ");
            console.log(angular.copy(scope.ActSession));//this is from LS b4 init
            scope.ActSession = actSession ;//this is actsession from LS after init
            console.log("Aft bind and assign, page actSession:");
            console.log(angular.copy(actSession));
            console.log("Aft bind and assign, page actSession:");
            console.log(angular.copy(scope.ActSession));
        },
        refresh: refresh,
        setActSession: function (_sessionKey, _activityID) {
            console.log("b4 set");
            console.log(angular.copy(actSession));
            var arr = _sessionKey.split('_') || [];
            var skey = arr[0];
            var dtExpiry = arr[1];
            var dtNow = new Date();
            var objActSession = getValidActSessionBySID(skey, dtNow);
            console.log('dtexipiry : ' + dtExpiry);
            //not found in actSession and not old session key
            if (!objActSession && !dtExpiry) {
                objActSession = {
                    SID: skey,
                    AID: [],
                    CreatedDate: dtNow,
                    ExpiryDate: dtNow,
                    LastSavedIndex: -1
                }
                actSession.push(objActSession);
            }

            if (objActSession) {
                objActSession.AID.push(_activityID);
                objActSession.ExpiryDate = dtNow.setHours(dtNow.getHours() + 1, dtNow.getMinutes());
            }

            console.log("set skey");
            console.log(objActSession);
            console.log(actSession);

        },
        getActSessionKey: function (_activityID) {
            console.log("b4 get");
            console.log(angular.copy(actSession));
            var dtNow = new Date();
            for (var i = 0; i < actSession.length; i++) {
                var objActSession = actSession[i];

                if (objActSession && objActSession.hasOwnProperty('AID')) {
                    if (objActSession.AID && objActSession.ExpiryDate >= dtNow) {
                        var n = objActSession.AID.indexOf(_activityID);
                        if (n != -1) {
                            console.log("get skey");
                            console.log(objActSession.SID + "_" + objActSession.ExpiryDate);
                            return objActSession.SID + "_" + objActSession.ExpiryDate; 
                        }

                    }
                }
            }

            return null;
        }
    };

    init();

    return service;

});


/*
crmApp.factory('ActivitySessionService', ['$rootScope', 'localStorageService', '$filter', function ($rootScope, localStorageService, $filter) {
    //var _sessionKey = '';
    //var _activityID = 0;
    
    //Init
    var sessionIndex = -1;
      
    var actSession = localStorageService.get('ActSession') || [];   

    var AS =  { 
        setActSession: function (_sessionKey, _activityID) {
            var objActSession = AS.getActSessionBySID(_sessionKey);
            if (objActSession) { 
                if (objActSession.AID && objActSession.AID.length > 0) {
                   
                    objActSession.AID.push(_activityID);
                    var dtExpiry = new Date(objActSession.ExpiryDate);
                    dtExpiry.setHours(dtExpiry.getHours(), dtExpiry.getMinutes() + 30);
                    //dtExpiry.setHours(dtExpiry.getUTCHours(), dtExpiry.getUTCMinutes() + 30).toString(); 
                    objActSession.ExpiryDate = dtExpiry; 
                }
            }
            else {
                var dtNow = new Date(); 
                var dtExpiry = new Date();
                dtExpiry.setHours(dtExpiry.getHours() + 2);
                //dtExpiry.setHours(dtExpiry.getUTCHours() + 2)  //TODO Test when change comp time  
                //tblActSession.push({ SID: vm.SessionKey, AID: [vm.activity.ActivityID] });
                actSession.push({ SID: _sessionKey, AID: [_activityID], CreatedDate: dtNow, ExpiryDate: dtExpiry, LastSavedIndex: null }); 
            }
            resetActSession();
            var a = localStorageService.get('ActSession');
            console.log(a);
           
        },

        setLastSavedIndex: function (i) {

            actSession[sessionIndex].LastSavedIndex = i;
            resetActSession();
        },

        getActSessionBySID: function (_sessionKey) {
            var o = null;
            deleteExpiredSessions();
             
            getSessionIndexbySID(_sessionKey);
            if (sessionIndex != -1) {
                o = actSession[sessionIndex];
            } 
            return o;
        },

        getActSessionByAID: function (_activityID) {
            var o = null;
            deleteExpiredSessions();

            for (var i = 0; i < actSession.length; i++) {
                var objActSession = actSession[i];

                if (objActSession && objActSession.hasOwnProperty('AID')) {
                    if (objActSession.AID) {
                        var n = objActSession.AID.indexOf(_activityID);
                        if (n != -1) {
                            o = objActSession;
                            sessionIndex = i;
                            break;
                        }

                    }
                }
            }
            return o;
        } 
    };
    var getSessionIndexbySID = function (_sessionKey) {
        //var index = -1; 
        for (var i = 0; i < actSession.length; i++) {
            if (actSession[i] && actSession[i].SID == _sessionKey) {
                sessionIndex = i;
                break;
            }
        } 
    }

    var deleteExpiredSessions = function () {
        var dtNow = new Date(); 

        var m = $filter('filter')(actSession, function (o) {
            var dtExpiry = new Date(o.ExpiryDate); 
            return dtExpiry >= dtNow;
        });
        
        //if (arrToDelete.length > 0)
        if (m && m.length != actSession.length) { 
            actSession = m; 
            resetActSession();
        }
    }

    var resetActSession = function () {
        localStorageService.remove('ActSession');
        localStorageService.set('ActSession', actSession);
          
    }

    //// Bind to local storage service
    //localStorageService.bind($rootScope, 'ActSession', actSession);

    return AS;
}]); 

*/