appice.controller('appUsersController',
	function ($scope,appIceService) {
        var userType = 'I';
        $scope.val = 'all';
    function init(){
    	initDateRange();
        $scope.getAppUsers('I');
        
        $('.theme-select').on('click',function(){
            var data = $(this).attr('data-attr');
            if(data == 'all'){
                $('#swiu').text('All');
                $scope.getUsers('');
            }
            else{
                $('#swiu').text( (data =='I')? 'Active' : 'InActive Users' );
                $scope.getUsers(data);
            }
        });
        
        $scope.getDauWauMau();
    }
    
   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.getDauWauMau();
       });
    }
    
    $scope.getDauWauMau = function(){
    	var dateArgs = {
            args:JSON.stringify({
                startDate_C: semusiCommon.dateRange.currentStartDate,
                endDate_C: semusiCommon.dateRange.currentEndDate,
                startDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousStartDate),
                endDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousEndDate),
                startDate_CNew:semusiCommon.dateRange.currentStartDateNew,
                endDate_CNew:semusiCommon.dateRange.currentEndDateNew,
                startDate_PNew:semusiCommon.dateRange.previousStartDateNew,
                endDate_PNew:semusiCommon.dateRange.previousEndDateNew                  
            })
    	}
    	var promise = appIceService.getDauWauMau(dateArgs.args);
    	promise.then(function(result){
        $("#overlay").hide();
    		if(result){
          $scope.DAU= (result.dau)? parseInt(result.dau):result.dau;
          $scope.WAU= (result.wau)? parseInt(result.wau):result.wau;
          $scope.MAU = (result.mau)? parseInt(result.mau):result.mau;
    		}
    	}).catch(function(error){
            $("#overlay").hide();
        });
    }
    /* code for platform filter function  by pranay */


    $scope.getDauWauMauPlatformFilter = function() {
        var dateArgs = {
            args:JSON.stringify({
                startDate_C: semusiCommon.dateRange.currentStartDate,
                endDate_C: semusiCommon.dateRange.currentEndDate,
                startDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousStartDate),
                endDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousEndDate),
                startDate_CNew:semusiCommon.dateRange.currentStartDateNew,
                endDate_CNew:semusiCommon.dateRange.currentEndDateNew,
                startDate_PNew:semusiCommon.dateRange.previousStartDateNew,
                endDate_PNew:semusiCommon.dateRange.previousEndDateNew
            })
        }
        var promise = appIceService.getDauWauMauWithPlatform(dateArgs.args);
        promise.then(function (result) {

            if($scope.val == 'android') {
                $scope.DAU = (result.android.dau)? parseInt(result.android.dau):result.android.dau;
                $scope.WAU = (result.android.wau)? parseInt(result.android.wau):result.android.wau;
                $scope.MAU = (result.android.mau)? parseInt(result.android.mau):result.android.mau
            }

            if ($scope.val == 'ios') {
                $scope.WAU = (result.ios.wau)? parseInt(result.ios.wau):result.ios.wau;
                $scope.MAU = (result.ios.mau)? parseInt(result.ios.mau):result.ios.mau                
                $scope.DAU = (result.ios.dau)? parseInt(result.ios.dau):result.ios.dau;
            }

            if ($scope.val == 'web') {
                $scope.WAU = (result.web.wau)? parseInt(result.web.wau):result.web.wau;
                $scope.MAU = (result.web.mau)? parseInt(result.web.mau):result.web.mau                
                $scope.DAU = (result.web.dau)? parseInt(result.web.dau):result.web.dau;
            }

        }).catch(function (error) {
             
        });

        if ($scope.val == 'all') {
            var promise2 = appIceService.getDauWauMau(dateArgs.args);
            promise2.then(function (result) {
            if($scope.val == 'all') {
    			$scope.DAU = (result.dau)? parseInt(result.dau):result.dau;
    			$scope.WAU = (result.wau)? parseInt(result.wau):result.wau;
    			$scope.MAU = (result.mau)? parseInt(result.mau):result.mau; 
            }
            })
            .catch(function (error) {
                 
            })
        }
         
            showAppUsers(userType);

        // NOT TO BE DELETED
        // promise3 = appIceService.getAppUsers(userType, $scope.val)
        // promise3.then(function (result) {
         
        //     result.data.forEach(value => {
        //         if($scope.val == value.platform.toLowerCase()) {
         
        //         }
        //     });
        // })
        // .catch(function (error) {
         
        // })
    }
    
    /*________________________ end code section ___________*/
    $scope.getUsers = function(userType){
    	$scope.getAppUsers(userType);
    }
    showAppUsers = function(userType){
        $('#tblUsers').on('preXhr.dt', function ( e, settings, data ) {
            data.uniqueNumber = semusiCommon.randomNumber()
        } )
            .DataTable( {
            "bDestroy": true,
            "processing": true,
            "language": {
                "processing": "<img  style='width: 130px; height: 100px; margin-left: 28%; position: absolute; margin-top: 13%;' src='../assets/img/global_loader.gif'> "
             },
            "serverSide": true,
            "stateSave": true,
            "ajax": {
                method: 'get',           
                url:semusiCommon.API_PARTS.users.r+"/getAppUsers",
                data: {
                    "api_key"       :semusiCommon.getActiveUser.api_key,
                    "app_id"        :semusiCommon.ACTIVE_APP_ID,
                    "uniqueNumber"     :semusiCommon.randomNumber(),
                    "type"          : userType,
                    "platform"      :$scope.val,
                },
                statusCode:{
                    404:function(){
                        showErrorMsg()
                    },
                    401:function(){
                        showErrorMsg()
                    },
                    200:function(){
                        $('#overlay').hide();
                    },
                    504:function(){
                        showErrorMsg()
                    }
                }
            },
            "columns": [
                { "data": "alias" },
                { "data": "fs" , "bSortable": true },
                { "data": "ls" ,  "bSortable": true},
                { "data": "sc" ,  "bSortable": false},
                // { "data": "ad" ,  "bSortable": false},   hide for now 
                { "data": "ci" ,  "bSortable": false}
            ],
            "order": [[ 1, "desc" ]]
        });
        function showErrorMsg(){
            $("#messagebox").text("Something's Wrong Here");
            $("#message").show();
            setTimeout(() => {
                $("#message").hide();
                location.reload(true);
            },3000)
        }
    }
    $scope.getAppUsers = function(userType){

        showAppUsers(userType);
    }

    init();
});
