appice.controller('appGroupsController',function ($scope,appIceService,$routeParams,$location) {

    function init(){
        $scope.cAppsSessionArr;
        $scope.cGroupsSessionArr;
        $scope.edit = false;
        semusiCommon.setDateRange(null,null);
        initDateRange();
        getOtherAppGroups();
        //getAppsAverageSession();
        //getGroupsAverageSession();
    }

    $scope.competingAppsIdArr = [];
    function getOtherAppGroups() {
        promise = appIceService.getOtherAppGroups();
        promise.then(function (groups) {
            $('#overlay').hide();
            $scope.groups = groups;
            $scope.gCompetingList = [];
            $scope.gCompeting = [];
            $scope.sCompetingList = [];
            $scope.competingList = [];
            groups.forEach(function (group) {
                //if(group.type == "system"){
                group.list.forEach(function (item) {
                    //item.addedOn = moment(item.addedOn*1000).format('DD-MM-YYYY');
                    $scope.competingAppsIdArr.push(item.id);
                    //$scope.competingList.push({id:item.id,name:item.name,package:item.package,urlscheme:item.urlscheme,addedOn:item.addedOn});
                })
                // $scope.sCompetingList.push({_id:group._id,appid:group.appid,name:group.name,description:group.description,type:group.type,list:$scope.competingList})

                //}
            })

            getAppsAverageSession();
            showCompetingApps();
        })
        .catch(function(error){
            $('#overlay').hide();
        });
    }
    /// get competing apps data session wise///
    function getAppsAverageSession() {
        promise = appIceService.getAppsAverageSession($scope.competingAppsIdArr);
        promise.then(function (compApps) {
            $('#overlay').hide();
            if (compApps && compApps != undefined) {
                $scope.cAppsSessionArr = compApps.data;
                populateCompetingAppSessiondata();
            }
        })
        .catch(function(){
            $('#overlay').hide();
        });
    }
    /// get competing apps data session wise end ///

    /// get competing apps groups data session wise///
    function getGroupsAverageSession() {
        promise = appIceService.getGroupsAverageSession();
        promise.then(function (compGroups) {
            if (compGroups && compGroups != undefined) {
                $scope.cGroupsSessionArr = compGroups.data;
                populateCompetingGroupsSessiondata();
            }
        });
    }
    /// get competing apps groups data session wise end///
    function populateCompetingGroupsSessiondata() {
        var platform = $("#ddlPlatform").val();
        $scope.groupSessionData = [];
        $scope.groupSessionDatas = [];
        var aSessionData = [];
        var avgKeys;
        var avgMinSecKeys;
        $scope.groupKeyArr = [];
        $scope.groupObjArr = [];
        $scope.cGroupsSessionArr.forEach(function (gSession) {
            if (gSession['android']) {
                aSessionData = Object.keys(gSession['android'])
            }

            $scope.groupSessionData = _.union(aSessionData);
            $scope.groupSessionData.forEach(function (groupName) {
                $scope.groupSessionDatas.push(groupName)
            })
            if (gSession['android']) {
                $scope.groupSessionData.forEach(function (keys) {
                    if (gSession['android'] && gSession['android'][keys] && gSession['android'][keys]['asl']) {
                        avgKeys = Object.keys(gSession['android'][keys]['asl'])
                        avgKeys.forEach(function (k) {
                            var obj = {};
                            obj[k] = gSession['android'][keys]['asl'][k];
                            $scope.groupKeyArr.push(obj)
                        })
                    }
                })
                if ($scope.groupKeyArr.length > 0) {
                    var map = $scope.groupKeyArr
                        .reduce(function (map, obj) {
                            var key = Object.keys(obj)[0];
                            map[key] ?
                                map[key].push(obj[key]) :
                                map[key] = [obj[key]];
                            return map;
                        }, {});

                    // convert above result to a list with objects.
                    $scope.compGroupsData = Object.keys(map)
                        .map(function (key) {
                            var obj = {};
                            obj[key] = map[key];
                            return obj;
                        })
                }
                /// App Wise Avrage session in minutes and seconds////
                var sessonLength;
                var auTotal = 0;
                var aslTotal = 0;

                avgMinSecKeys = Object.keys(gSession['android']);
                avgMinSecKeys.forEach(function (appName, key) {
                    var obj = {};
                    obj[appName] = {};
                    if (appName) {
                        ///// for session count section//
                        if (gSession['android'][appName]['au']['1']) {
                            auTotal += gSession['android'][appName]['au']['1'];
                            obj[appName]['au'] = auTotal;
                        }
                        if (gSession['android'][appName]['au']['10+']) {
                            auTotal += gSession['android'][appName]['au']['10+'];
                            obj[appName]['au'] = auTotal;
                        }
                        if (gSession['android'][appName]['au']['8-10']) {
                            auTotal += gSession['android'][appName]['au']['8-10'];
                            obj[appName]['au'] = auTotal;
                        }
                        if (gSession['android'][appName]['au']['6-8']) {
                            auTotal += gSession['android'][appName]['au']['6-8'];
                            obj[appName]['au'] = auTotal;
                        }
                        if (gSession['android'][appName]['au']['2-5']) {
                            auTotal += gSession['android'][appName]['au']['2-5'];
                            obj[appName]['au'] = auTotal;
                        }
                        auTotal = 0;
                        /// total session duration section///
                        if (gSession['android'][appName]['asl']['5+']) {
                            aslTotal += gSession['android'][appName]['asl']['5+'];
                            obj[appName]['asl'] = aslTotal;
                        }
                        if (gSession['android'][appName]['asl']['3-5']) {
                            aslTotal += gSession['android'][appName]['asl']['3-5'];
                            obj[appName]['asl'] = aslTotal;
                        }
                        if (gSession['android'][appName]['asl']['1-3']) {
                            aslTotal += gSession['android'][appName]['asl']['1-3'];
                            obj[appName]['asl'] = aslTotal;
                        }
                        if (gSession['android'][appName]['asl']['0.5-1']) {
                            aslTotal += gSession['android'][appName]['asl']['0.5-1'];
                            obj[appName]['asl'] = aslTotal;
                        }
                        if (gSession['android'][appName]['asl']['<30']) {
                            aslTotal += gSession['android'][appName]['asl']['<30'];
                            obj[appName]['asl'] = aslTotal;
                        }
                        aslTotal = 0;
                        $scope.groupObjArr.push(obj);
                    }
                })
                if ($scope.groupObjArr.length > 0) {
                    var appName;
                    var avgSession = 0;
                    var auSession = 0;
                    var aslSession = 0;
                    var mins = 0;
                    var seconds = 0;
                    $scope.groupAvgSession = [];
                    $scope.groupObjArr.forEach(function (item) {
                        appName = Object.keys(item);
                        appName.forEach(function (appKeys) {
                            auSession = item[appKeys]['au'];
                            aslSession = item[appKeys]['asl'];
                            avgSession = parseFloat((aslSession / auSession)).toFixed(2);
                            var mins = parseInt(avgSession / 60);
                            var seconds = parseInt(avgSession - (mins * 60));
                             
                            if (!isNaN(mins)) {
                                mins = mins;
                            } else {
                                mins = 0;
                            }
                            if (!isNaN(seconds)) {
                                seconds = seconds;
                            } else {
                                seconds = 0;
                            }
                            $scope.groupAvgSession.push({ mins: mins, seconds: seconds });
                            auSession = 0;
                            aslSession = 0;
                            avgSession = 0;
                            mins = 0;
                            seconds = 0;
                        })
                    })
                }

            }
        })

    }
    /// get competing apps data session wise end///
    function populateCompetingAppSessiondata() {
        var platform = $("#ddlPlatform").val();
        $scope.sessionData = [];
        var aSessionData = [];
        var avgKeys;
        var avgMinSecKeys;
        $scope.keyArr = [];
        if ($scope.cAppsSessionArr['android']) {
            aSessionData = Object.keys($scope.cAppsSessionArr['android'])
        }
        $scope.sessionData = _.union(aSessionData);
         
        if ($scope.cAppsSessionArr['android']) {
            $scope.sessionData.forEach(function (keys) {
                if ($scope.cAppsSessionArr['android'] && $scope.cAppsSessionArr['android'][keys] && $scope.cAppsSessionArr['android'][keys]['asl']) {
                    avgKeys = Object.keys($scope.cAppsSessionArr['android'][keys]['asl'])
                    avgKeys.forEach(function (k) {
                        var obj = {};
                        obj[k] = $scope.cAppsSessionArr['android'][keys]['asl'][k];
                        $scope.keyArr.push(obj)
                    })
                }
            })
            if ($scope.keyArr.length > 0) {
                var map = $scope.keyArr
                    .reduce(function (map, obj) {
                        var key = Object.keys(obj)[0];
                        map[key] ?
                            map[key].push(obj[key]) :
                            map[key] = [obj[key]];
                        return map;
                    }, {});

                // convert above result to a list with objects.
                $scope.compAppsData = Object.keys(map)
                    .map(function (key) {
                        var obj = {};
                        obj[key] = map[key];
                        return obj;
                    })
            }
            /// App Wise Avrage session in minutes and seconds////
            var sessonLength;
            var auTotal = 0;
            var aslTotal = 0;
            $scope.objArr = [];
            $scope.avgSessions = [];
            var currentTotal = 0;
            var currentU = 0;
            currentTotal += $scope.cAppsSessionArr['android']['currentTsd'];
            currentU += $scope.cAppsSessionArr['android']['currentTotalSc'];
            currentTotal += $scope.cAppsSessionArr['ios']['currentTsd'];
            currentU += $scope.cAppsSessionArr['ios']['currentTotalSc'];
            var mins = 0;
            var seconds = 0;

            // var currentTotal = parseFloat((currentTotal / currentU)).toFixed(2);
            // if (currentTotal >= 0) {
            //     mins = parseInt(currentTotal / 60);
            //     seconds = parseInt(currentTotal - (mins * 60));
             
            // }
            // $scope.avgSessions.push({mins:mins+" mins",seconds:seconds+" secs"});
            var currentTotal = parseFloat((currentTotal / currentU)).toFixed(2);
            if (currentTotal >= 0) {
                mid = parseInt(currentTotal / 60);
                seconds = parseInt(currentTotal - (mid * 60));   
                mins = parseInt(mid/10);
                 
            }
            $scope.avgSessions.push({mins:mins+" mins",seconds:seconds+" secs"});

            avgMinSecKeys = Object.keys($scope.cAppsSessionArr['android']);
            avgMinSecKeys.forEach(function(appName,key){
                var obj = {};
                obj[appName] = {};
               /*if(appName != "currentSc" && appName != "previousSc" && appName != "currentAsl" && appName != "previousAsl"){
                ///// for session count section//
                    
                    if($scope.cAppsSessionArr['android'][appName]['au']['1']){
                        auTotal += $scope.cAppsSessionArr['android'][appName]['au']['1'];
                        obj[appName]['au'] = auTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['au']['10+']){
                        auTotal += $scope.cAppsSessionArr['android'][appName]['au']['10+'];
                        obj[appName]['au'] = auTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['au']['8-10']){
                        auTotal += $scope.cAppsSessionArr['android'][appName]['au']['8-10'];
                        obj[appName]['au'] = auTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['au']['6-8']){
                        auTotal += $scope.cAppsSessionArr['android'][appName]['au']['6-8'];
                        obj[appName]['au'] = auTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['au']['2-5']){
                        auTotal += $scope.cAppsSessionArr['android'][appName]['au']['2-5'];
                        obj[appName]['au'] = auTotal;
                    }
                    auTotal = 0;
                    /// total session duration section///
                    if($scope.cAppsSessionArr['android'][appName]['asl']['5+']){
                        aslTotal += $scope.cAppsSessionArr['android'][appName]['asl']['5+'];
                        obj[appName]['asl'] = aslTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['asl']['3-5']){
                        aslTotal += $scope.cAppsSessionArr['android'][appName]['asl']['3-5'];
                        obj[appName]['asl'] = aslTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['asl']['1-3']){
                        aslTotal += $scope.cAppsSessionArr['android'][appName]['asl']['1-3'];
                        obj[appName]['asl'] = aslTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['asl']['0.5-1']){
                        aslTotal += $scope.cAppsSessionArr['android'][appName]['asl']['0.5-1'];
                        obj[appName]['asl'] = aslTotal;
                    }
                    if($scope.cAppsSessionArr['android'][appName]['asl']['<30']){
                        aslTotal += $scope.cAppsSessionArr['android'][appName]['asl']['<30'];
                        obj[appName]['asl'] = aslTotal;
                    }
                    aslTotal = 0;
                    $scope.objArr.push(obj);
               }*/
            })
            if($scope.objArr.length > 0){
                var appName;
                var avgSession = 0;
                var  auSession = 0;
                var  aslSession = 0;
                var mins = 0;
                var seconds = 0;
                $scope.avgSessions = [];
                $scope.objArr.forEach(function(item){
                    appName = Object.keys(item);
                    appName.forEach(function(appKeys){
                         
                        auSession = item[appKeys]['au'];
                        aslSession = item[appKeys]['asl'];
                        avgSession =  parseFloat((aslSession/auSession)).toFixed(2);
                        mins = parseInt(avgSession/60);
                        seconds = parseInt(avgSession-(mins*60));
                        if(!isNaN(mins)){
                            mins = mins;
                        }else{
                            mins = 0;
                        }
                        if(!isNaN(seconds)){
                            seconds = seconds;
                        }else{
                            seconds = 0;
                        }
                        $scope.avgSessions.push({mins:mins+" mins",seconds:seconds+" secs"});

                        auSession = 0;
                        aslSession = 0;
                        avgSession = 0;
                        mins = 0;
                        seconds = 0;
                    })
                })
            }

        }

    }


    function initDateRange(){
        $('#advance-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));

        var _period = [moment(semusiCommon.dateRange.currentStartDate*1000).format(semusiCommon.getDateFormatt()),moment(semusiCommon.dateRange.currentEndDate*1000).format(semusiCommon.getDateFormatt())];
        semusiCommon.setPeriod(_period);

        $('#advance-daterange').daterangepicker({
            format: semusiCommon.getDateFormatt(),
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            minDate: '01/01/2012',
            maxDate: new Date(),
            dateLimit: { days: 365 },
            showDropdowns: true,
            showWeekNumbers: false,
            timePicker: false,
            timePickerIncrement: 1,
            timePicker12Hour: true,
            ranges: {
               'Today': [moment(), moment()],
               'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
               'Last 7 Days': [moment().subtract(6, 'days'), moment()],
               'Last 30 Days': [moment().subtract(29, 'days'), moment()],
               'This Month': [moment().startOf('month'), moment().endOf('month')],
               'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            opens: 'left',
            drops: 'down',
            buttonClasses: ['btn', 'btn-sm'],
            applyClass: 'btn-primary',
            cancelClass: 'btn-default',
            separator: ' to ',
            locale: {
                applyLabel: 'Submit',
                cancelLabel: 'Cancel',
                fromLabel: 'From',
                toLabel: 'To',
                customRangeLabel: 'Custom',
                daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
                monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                firstDay: 1
            }
        }, function(start, end, label) {
            semusiCommon.setDateRange(start,end);
            $('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));
            calStartDate = start.format(semusiCommon.getDateFormatt());
            calEndDate = end.format(semusiCommon.getDateFormatt());
            i_maxInstallValue=0;
            u_maxInstallValue=0;
            getAppsAverageSession();
            //getGroupsAverageSession();
            var _period = [moment(semusiCommon.dateRange.currentStartDate*1000).format(semusiCommon.getDateFormatt()),moment(semusiCommon.dateRange.currentEndDate*1000).format(semusiCommon.getDateFormatt())];
            semusiCommon.setPeriod(_period);
        });
    }

    $scope.competingApps = [];
    function showCompetingApps(){
        promise = appIceService.getCompetingAppsAppWise($scope.competingAppsIdArr);
        promise.then(function(apps) {
            $('#overlay').hide();
            if(apps.data && apps.data.length > 0){
                $scope.competingApps = apps.data.map(apps =>{
                  if(apps.competingapps == 'Self' || apps.competingapps == 'self'){
                      apps.competingapps = semusiGlobal.apps[semusiCommon.ACTIVE_APP_ID].name;
                  }
                  return apps;
                })
                //$scope.competingApps = apps.data;
               /* var vennSets = [];
                apps.data.forEach(function(item,key){
                    vennSets.push({"sets":[key],"label":item.competingapps+'\n   Users:'+item.total,"size":item.total});
                })
                var tempArr = [];
                vennSets.forEach(function(data,key){
                    if(key != 0){
                        tempArr.push({"sets": [0,  key], "size": data.size})
                    }
                });
                var sets = vennSets.concat(tempArr);
                var chart = venn.VennDiagram()
                 .width(500)
                 .height(400).fontSize('10px');
                var div = d3.select("#venn")
                div.datum(sets).call(chart);
                d3.selectAll("#venn .venn-circle path")
                    .style("fill-opacity", .8);

                d3.selectAll("#venn text").style("fill", "#242a30");*/

            }
        })
        .catch(function(){
            $('#overlay').hide();
        });
    }

    function clearFields(){
        $scope.id="";
        $scope._id = "";
        $scope.appname = "";
        $scope.package = "";
        $scope.urlscheme = "";
        $scope.edit = false;
    }

    $scope.saveOtherAppGroup = function(){
        $('.groupDescError').css({'color':'red','display':'none'}); 
        $('.groupnameError').css({'color':'red','display':'none'});
		//   Validating the userinput to contain only allowing letters, numbers, space, commas, periods?
		var regex = /^[\.a-zA-Z0-9,!? ]*$/;
	    if($scope.groupname==undefined || $scope.groupname=="" || !regex.test($scope.groupname)) {
            $('.groupnameError').css({'color':'red','display':'block'});
			return false;  
		}
		
		// for decription 
		if($scope.groupdescription==undefined || $scope.groupdescription=="" || !regex.test($scope.groupdescription)) {
            $('.groupDescError').css({'color':'red','display':'block'}); 
			return false;  
		}
        $('#group-dialog').modal('hide');
        var group = {
            name:$scope.groupname,
            description: $scope.groupdescription,
            appid:semusiCommon.ACTIVE_APP_ID
        }
        promise = appIceService.saveOtherAppGroup(group);
        promise.then(function(data) {
            getOtherAppGroups();
            clearFields();
        });
    }

    $scope.editGroup = function(group){
        $scope.id = group._id;
        $scope.groupname = group.name;
        $scope.groupdescription = group.description;
        $scope.edit = true;
    }

    $scope.deleteGroup = function(id){
        if(confirm("Are you sure to delete this group?.")){
            promise = appIceService.deleteOtherAppGroup(id);
            promise.then(function(data) {
                getOtherAppGroups();
            });
        }
    }
    $scope.updateOtherAppGroup = function(){
        $('.groupDescError').css({'color':'red','display':'none'}); 
        $('.groupnameError').css({'color':'red','display':'none'});
		//   Validating the userinput to contain only allowing letters, numbers, space, commas, periods?
		var regex = /^[\.a-zA-Z0-9,!? ]*$/;
	    if($scope.groupname==undefined || $scope.groupname=="" || !regex.test($scope.groupname)) {
            $('.groupnameError').css({'color':'red','display':'block'});
			return false;  
		}
		
		// for decription 
		if($scope.groupdescription==undefined || $scope.groupdescription=="" || !regex.test($scope.groupdescription)) {
            $('.groupDescError').css({'color':'red','display':'block'}); 
			return false;  
		}
        $('#group-dialog').modal('hide');
        var group = {
            name:$scope.groupname,
            description: $scope.groupdescription,
            appid:semusiCommon.ACTIVE_APP_ID
        }
        promise = appIceService.updateOtherAppGroup(group,$scope.id);
        promise.then(function(data) {
            getOtherAppGroups();
            clearFields();
        });
    }

    $scope.setGroupId = function(id){
        clearFields();
        $scope.id = id;
    }

    $scope.addAppToGroup = function () {

        $('.appNameError').css({'color':'red','display':'none'}); 
        // $('.addRegexError').css({'color':'red','display':'none'});

		//   Validating the userinput in App name to contain only allowing letters, numbers, space, commas, periods?
		var regex = /^[\.a-zA-Z0-9,!? ]*$/;
	    if($scope.appname==undefined || $scope.appname=="" || !regex.test($scope.appname)) {
            $('.appNameError').css({'color':'red','display':'block'});
			return false;  
		}
        var flag = true;
        $scope.addError = false;
        if ($scope.package == "") {
            $scope.addError = true;
            flag = false;
            return false;
        }
        if (flag == true) {
            var app = {
                name: $scope.appname,
                package: $scope.package,
                urlscheme: $scope.urlscheme
            }
            promise = appIceService.addAppToGroup(app, $scope.id);
            promise.then(function (data) {
                if (data.msg) {
                    alert("This app already exists in this group.");
                    return;
                }
                angular.element('#groupapps-dialog').modal('hide');
                getOtherAppGroups();
                clearFields();
            });
        }

    }
    $scope.editGroupApp = function (app, groupid) {
        $scope.id = groupid;
        $scope._id = app.id;
        $scope.appname = app.name;
        $scope.package = app.package;
        $scope.urlscheme = app.urlscheme;
        $scope.edit = true;
    }
    $scope.updateAppToGroup = function () {
	//   Validating the userinput in App name to contain only allowing letters, numbers, space, commas, periods?
		var regex = /^[\.a-zA-Z0-9,!? ]*$/;
	    if($scope.appname==undefined || $scope.appname=="" || !regex.test($scope.appname)) {
            $('.appNameError').css({'color':'red','display':'block'});
			return false;  
		}
        $('#group-dialog').modal('hide');
        var app = {
            name: $scope.appname,
            package: $scope.package,
            urlscheme: $scope.urlscheme,
            id: $scope._id
        }
        promise = appIceService.updateAppToGroup(app, $scope.id);
        promise.then(function (data) {
            if (data.msg) {
                alert("This app already exists in this group.");
                return;
            }
            getOtherAppGroups();
            clearFields();
        });
    }

    $scope.deleteAppFromGroup = function(_id,groupid){
        if(confirm("Are you sure to delete this app?")){
            promise = appIceService.deleteAppFromGroup(_id,groupid);
            promise.then(function(data) {
                getOtherAppGroups();
            });
        }
    }

    $scope.cancel = function(){
        clearFields();
    }

    init();

});
