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

    $scope.getSession = function(){

        $scope.session              = {};
        $scope.session.dau          = 0;
        $scope.session.mau          = 0;
        $scope.session.aUsers       = 0;
        $scope.session.currentTotal = 0;
        $scope.totalDuration        = 0;
        $scope.avgSessionTime       = 0;
        $scope.previousSession      = 0;

        var args = JSON.stringify({
                    /*startDate_C:semusiCommon.addOffset(semusiCommon.dateRange.currentStartDate),
                    endDate_C:semusiCommon.addOffset(semusiCommon.dateRange.currentEndDate),
                    startDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousStartDate),
                    endDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousEndDate)         */
                    startDate_C:semusiCommon.dateRange.currentStartDateNew,
                    endDate_C:semusiCommon.dateRange.currentEndDateNew,
                    startDate_P:semusiCommon.dateRange.previousStartDateNew,
                    endDate_P:semusiCommon.dateRange.previousEndDateNew            
                });
        var promise = appIceService.getChatBotSession($routeParams.app_id, args);
        promise.then(function(data){
            if(data){
                $scope.session = data;
                // manage platform sessions
                if($scope.session.current){
                    $scope.session.current.forEach(function(platform, index){
                        var keys = Object.keys(platform);
                        keys.forEach(function(p){
                            var count = 0;
                            $scope.session.current[index][p].forEach(function(time, k){
                                var timeKey = Object.keys(time);
                                count += $scope.session.current[index][p][k][timeKey];
                            });
                            $('#'+p).text(count);

                            // previous session information
                            if($scope.session.previous[p]){
                                $('#'+p+'_percent').html('NA');
                                $scope.previousSession += $scope.session.previous[p];

                                var percentChange =($scope.session.previous[p]==0) ? 100: parseFloat(count/$scope.session.previous[p]*100).toFixed(2);
                                if(percentChange>0 && $scope.session.previous[p] > 0){
                                    var changeSign = '<div style="font-size:10px;"><i class="fa fa-2x fa-arrow-up"></i> '+parseInt(percentChange) +' %</div>';
                                    $('#'+p+'_percent').html(changeSign);
                                }
                                else if(percentChange<0 && $scope.session.previous[p] > 0){
                                    percentChange=percentChange*-1;
                                    changeSign = '<div style="font-size:10px;"><i class="fa fa-2x fa-arrow-down"></i> '+parseInt(percentChange) +' %</div>';
                                    $('#'+p+'_percent').html(changeSign);
                                }
                            }                            
                        });
                    });
                }

                // total active users
                if($scope.session.activeUsers){
                    var pKeys = Object.keys($scope.session.activeUsers);
                    pKeys.forEach(function(p){
                         
                        $scope.session.aUsers = parseInt($scope.session.activeUsers[p]);
                    });
                }
                else{
                    $scope.session.dau = 0;
                    $scope.session.mau = 0;
                    $scope.session.aUsers = 0;
                }

                // manage duration
                if($scope.session.periodDuration > 0){
                    $scope.avgSessionTime = (($scope.session.totalDuration/$scope.session.periodDuration)/60).toFixed(2);
                    $scope.totalDuration  = ($scope.session.totalDuration/60).toFixed(2);
                }

                if($scope.previousSession > 0){
                    var percentChange =($scope.previousSession==0) ? 100: parseFloat($scope.session.currentTotal/$scope.previousSession*100).toFixed(2);
                    if(percentChange>0 && $scope.previousSession > 0){
                        var changeSign = '<div style="font-size:10px;"><i class="fa fa-2x fa-arrow-up"></i> '+parseInt(percentChange) +' %</div>';
                        $('#previousTotal').html(changeSign);
                    }
                    else if(percentChange<0 && $$scope.previousSession > 0){
                        percentChange=percentChange*-1;
                        changeSign = '<div style="font-size:10px;"><i class="fa fa-2x fa-arrow-down"></i> '+parseInt(percentChange) +' %</div>';
                        $('#previousTotal').html(changeSign);
                    }
                }                
            }
        })
    }

    $scope.getChatBotEvents = function(){
        $scope.messageIn            = 0;
        $scope.messageOut           = 0;

        var args = JSON.stringify({
                    startDate:semusiCommon.dateRange.currentStartDate,
                    endDate:semusiCommon.dateRange.currentEndDate,
                    startDateNew:semusiCommon.dateRange.currentStartDateNew,
                    endDateNew:semusiCommon.dateRange.currentEndDateNew                    
                });
        var promise = appIceService.getChatBotEvents($routeParams.app_id, args);
        promise.then(function(data){
            var labels = []
            if(data){
                data.forEach(function(item){
                    if(item.facebook){
                       data['facebook'] = _.extend(item.facebook);
                    }
                });
                if(data['facebook']){
                    labels = Object.keys(data['facebook']);
                    labels.forEach(function(date, key){
                        if(data['facebook'][date]['incoming']){
                            $scope.messageIn += data['facebook'][date]['incoming'];
                        }
                        if(data['facebook'][date]['outgoing']){
                            $scope.messageOut += data['facebook'][date]['outgoing'];
                        }
                    });
                }
            }
        });
    }

    var initDateRange = function(){
        semusiCommon.setDateRange(null,null);

        $('#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;
            
            var _period = [moment(semusiCommon.dateRange.currentStartDate*1000).format(semusiCommon.getDateFormatt()),moment(semusiCommon.dateRange.currentEndDate*1000).format(semusiCommon.getDateFormatt())];
            semusiCommon.setPeriod(_period);

            $scope.getSession();
            $scope.getChatBotEvents();
        });

        $scope.getSession();
        $scope.getChatBotEvents();
    }
    initDateRange();

    var installCohortChart=document.getElementById('installCohort');
    if(installCohortChart){
            $('#ddlCohortDateFilter').change(function() {
                maxInstallValue=0;
                filterObject=semusiCommon.getFilterObject($(this).val());
                //semusiChart.getInstallUninstallCohortData();
            });
            $('#chkPercentage').bootstrapSwitch('state', false);
            $('.bootstrap-switch-label').css("background","#f5f5f5");
            $('#chkPercentage').on('switchChange.bootstrapSwitch', function (event, state) {
                if(state){
                    var text=$('#chkPercentage').bootstrapSwitch('offText');
                    $('#chkPercentage').bootstrapSwitch('labelText',text);
                    
                }
                else{
                    var text=$('#chkPercentage').bootstrapSwitch('onText');
                    $('#chkPercentage').bootstrapSwitch('labelText',text);
                }
                
                
                semusiChart.switchState = state;
                getInstallUninstallCohortData();
                
            });
            $("#txtFromDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            $("#txtToDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            $("#txtStartDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            $("#txtEndDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            //Assign default dates:
            $("#txtFromDate").val(semusiCommon.getCurrentYearStartDate());
            $("#txtToDate").val(semusiCommon.getCurrentDate());


            $('.theme-select').on('click',function(){
                var data = $(this).attr('data-attr');
                if(data == 'all'){
                    $('#swiu').text('All');
                }else if(data == 'android'){
                    $('#swiu').text('Android');
                }else if(data == 'ios'){
                    $('#swiu').text('iOS');
                }else if(data == 'web'){
                    $('#swiu').text('Web');
                }
                $("#ddlPlatform").val(data)
                $("#ddlPlatform").val();
                semusiCommonData.populateSourceWiseInstallsUninstalls($("#ddlPlatform").val());
            });
            $('#swiu').text('All');
    }

    var getInstallUninstallCohortData = function(filter){

        var filter=$('#ddlCohortDateFilter').val();
        var fromDate=$("#txtFromDate").val();
        var toDate=$("#txtToDate").val();
        var startDate = semusiCommon.getEpochFromDate(moment(fromDate).startOf('day'));
        var endDate = semusiCommon.getEpochFromDate(moment(toDate).endOf('day'));

        var startDateNew = moment(startDate).format('YYYY-MM-DD');
        var endDateNew = moment(endDate).format('YYYY-MM-DD');

        if(startDate>endDate){
            alert("From date cannot be greater than To date.");
            return;
        }
        
        var periodType;
        switch(filter){
            case "daily":
                periodType="d";
                break;
            case "weekly":
                periodType="w";
                break;
            case "monthly":
                periodType="m";
                break;
            case "yearly":
                periodType="y";
                break;
            default:
                periodType="d";
                break;
        }

        var args = JSON.stringify({
                    startDate:startDate/1000,
                    endDate:endDate/1000,
                    startDateNew:startDateNew,
                    endDateNew:endDateNew,
                    periodtype:periodType,
                    metrices:[
                        {
                            
                        }
                    ]
                });

        var promise = appIceService.getChatBotCohort($routeParams.app_id, args);
        promise.then(function(data){
             
        });
    };

    getInstallUninstallCohortData();
    
    $scope.viewCohort = function(){
        getInstallUninstallCohortData();
    }

});

appice.filter( 'round', function() {
    return function( input ) {
        //return (input > 0)? (Math.round(input + "e+2")  + "e-2") : 0;
        return (input > 0)? (Math.round(input)) : 0;
    }
});