appice.controller('transitionalCampaignsController',function ($scope, appIceService, $routeParams) {
    jQuery.fn.dataTableExt.oSort['uk_date-asc']  = function(a,b) {
        var ukDatea = a.split('/');
        var ukDateb = b.split('/');

        var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
        var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

        return ((x < y) ? -1 : ((x > y) ?  1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
        var ukDatea = a.split('/');
        var ukDateb = b.split('/');

        var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
        var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

        return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
    };

    $scope.getTransitionalCampaigns = function(){
        $('#tblCampaigns').DataTable( {
            "bDestroy": true,
            "processing": true,
            "serverSide": true,
            "ajax": {
                method: 'get',           
                url:semusiCommon.API_PARTS.templates.w + "/getTransitionalCampaigns",
                data: {
                    api_key         :semusiCommon.getActiveUser.api_key,
                    app_id          :semusiCommon.ACTIVE_APP_ID,
                    uniqueNumber     :semusiCommon.randomNumber(),
                    args            :JSON.stringify({
                                        startDate : semusiCommon.dateRange.currentStartDate,
                                        endDate : semusiCommon.dateRange.currentEndDate,
                                        offset : semusiCommon.addOffset(0)
                                    })
                },
                statusCode:{
                    404:function(){
                        $("#overlay").hide();
                    },
                    200:function(){
                        $("#overlay").hide();
                    },
                    504:function(){
                        $("#overlay").hide();
                    }
                }
            },
            "columns": [
                { "data": "name"},
                { "data": "head"},
                { "data": "desc"},
                { "data": "reach", "bSortable": false },
                { "data": "pushedTo", "bSortable": false },
                { "data": "viewed", "bSortable": false },
                { "data": "dnr", "bSortable": false },
                { "data": "clicked", "bSortable": false},
                { "data": "timestamp", "sType": "uk_date"}
            ],
            "aoColumnDefs": [ 
                                {
                                    "aTargets": [ 8 ],
                                    "mData": "timestamp",
                                    "mRender": function ( data, type, full ) {
                                        return '<label value="'+ data +'">'+moment(data).format('D/MM/YYYY HH:mm:ss') +'</label>';
                                    }
                                }
                        ],
            "order": [[ 8, "desc" ]],
        });
    }
    
    // set date picker
    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.getTransitionalCampaigns();
        });

        $scope.getTransitionalCampaigns();
    }

    $scope.downloadCsv = function(){
        var args = JSON.stringify({
                            startDate : semusiCommon.dateRange.currentStartDate,
                            endDate : semusiCommon.dateRange.currentEndDate,
                            offset : semusiCommon.addOffset(0)
                        });
        //args = encodeURI(args);
        window.location = appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.w + '/downloadTransitionalCampaigns?api_key='+semusiCommon.getActiveUser.api_key+'&app_id='+semusiCommon.ACTIVE_APP_ID+'&args='+args+'&filename=transitional-campaign.csv');
        /*var promise = appIceService.downloadTransitionalCampaigns(semusiCommon);
        promise.then(function(response){
            if(response){
                 
            }
        });*/
    }

    if($routeParams.campid == undefined){
        // invoke function
        initDateRange(); 
    }
    else{
        // campaign details code snip
        $scope.createBarChartData = function(datasets){
             
            var chart = new CanvasJS.Chart("campaignGraph", {
                title: {
                    text: ""
                },
                legend: {
                   horizontalAlign: "center", // "center" , "right"
                   verticalAlign: "bottom",  // "top" , "bottom"
                   fontSize: 13
                },
                axisX:{
                    //title: "timeline",
                    intervalType: "month",
                    gridColor: "white"
                },
                axisY:{
                    gridColor: "white"
                },
                height: 400,
                data: datasets
            });

            chart.render();
        }

        $scope.campaignInfo = {};

        // get campaign stats information
        if($routeParams.campid){
            $scope.ctype = $routeParams.ctype;
            $scope.received = 0;
            $scope.viewed = 0;
            $scope.clicked = 0;
            $scope.ignored = 0;
            $scope.ctr = "0%";
            $scope.bestCity = 'NA';
            $scope.wrostCity = 'NA';
            $scope.bestTime = 'NA';
            $scope.wrostTime = 'NA';

            var promise = appIceService.getCampaignDetails($routeParams.campid, $routeParams.type);
            promise.then(function(data){
                if(data){
                    if(data.stats){
                        var platforms = ['android','ios','web'];
                        var dataObj = data.stats;
                        var aKeys = Object.keys(dataObj.android);
                        var iKeys = Object.keys(dataObj.ios);
                        var wKeys = Object.keys(dataObj.web);
                        var labels = _.union(aKeys, iKeys, wKeys);

                        labels = _.sortBy(labels, function(o) { 
                            var datestr = o.replace(/\_/g, "/");                
                            return (new Date(datestr));
                        });

                        var dataSets = [
                                {
                                    type: "column",
                                    color: "green",
                                    showInLegend: true,
                                    legendText: "Viwed",
                                    dataPoints: []
                                }, {
                                    type: "column",
                                    color: "blue",
                                    showInLegend: true,
                                    legendText: "Clicked",
                                    dataPoints: []
                                }, 
                                {
                                    type: "line",
                                    color: "yellow",
                                    showInLegend: true,
                                    legendText: "Ignored",
                                    dataPoints: []
                                }
                            ];

                        var index=0;
                        labels.forEach(function(key){  
                            var viewed = 0;  
                            var clicked = 0;
                            var ignored = 0; 
                            var received = 0;     
                                         
                            platforms.forEach(function(p){
                                if(dataObj[p][key]){
                                    var devices = Object.keys(dataObj[p][key]);
                                    devices.forEach(function(device){
                                        var cities = Object.keys(dataObj[p][key][device]);
                                        cities.forEach(function(city){
                                            // check campaign receive
                                            if(dataObj[p][key][device][city]['Campaign_Received']){
                                                $scope.received += dataObj[p][key][device][city]['Campaign_Received']; 
                                                received += dataObj[p][key][device][city]['Campaign_Received']; 
                                            }
                                            // check campaign viewed
                                            if(dataObj[p][key][device][city]['Campaign_Viewed']){
                                                $scope.viewed += dataObj[p][key][device][city]['Campaign_Viewed']; 
                                                viewed += dataObj[p][key][device][city]['Campaign_Viewed']; 
                                            }
                                            // check campaign clicked
                                            if(dataObj[p][key][device][city]['Campaign_Clicked']){
                                                $scope.clicked += dataObj[p][key][device][city]['Campaign_Clicked']; 
                                                clicked += dataObj[p][key][device][city]['Campaign_Clicked']; 
                                            }
                                            // check campaign delete
                                            if(dataObj[p][key][device][city]['Campaign_Deleted']){
                                                $scope.ignored += dataObj[p][key][device][city]['Campaign_Deleted']; 
                                                ignored += dataObj[p][key][device][city]['Campaign_Deleted']; 
                                            }
                                        });
                                    }); 
                                }                               
                            });

                            $scope.ctr = parseFloat(clicked/received*100).toFixed(2)+"%";
                            dataSets[0].dataPoints.push( { x: moment(key,"YYYY_MM_DD").toDate(), y: viewed });
                            dataSets[1].dataPoints.push( { x: moment(key,"YYYY_MM_DD").toDate(), y: clicked });
                            dataSets[2].dataPoints.push( { x: moment(key,"YYYY_MM_DD").toDate(), y: ignored });                
                        
                            // check conversion
                            if(data.stats.c > 0){
                                $scope.conversion = parseFloat(data.stats.c/received*100).toFixed(2);
                            }
                            else{
                                $scope.conversion = 0;
                            }
                        });

                        $scope.createBarChartData(dataSets);
                    }
                    // campaign information
                    if(data.campaign){
                        $scope.campaignInfo = data.campaign;
                        if($scope.campaignInfo.name == undefined){
                            $scope.campaignInfo.name = $scope.campaignInfo.template.notificationHeader;
                            $scope.campaignInfo.desc = $scope.campaignInfo.template.notificationDescription;
                        }
                        $scope.campaignInfo.startMoment = moment($scope.campaignInfo.timestamp).valueOf()/1000;
                        $scope.campaignInfo.startHrs = moment($scope.campaignInfo.timestamp).format('hA');
                        $scope.campaignInfo.timestamp = moment($scope.campaignInfo.timestamp).format(semusiCommon.getDateFormatt());
                    }
                    // get best and wrost city 
                    if(dataObj.bestCity){
                        $scope.bestCity = dataObj.bestCity
                    }
                    // get best and wrost city 
                    if(dataObj.wrostCity){
                        $scope.wrostCity = dataObj.wrostCity
                    }
                    // get best and wrost time 
                    if(dataObj.bestTime){
                        /*var duration = moment.duration(parseInt(dataObj.bestTime)-parseInt($scope.campaignInfo.startMoment));
                        var hours = moment(duration,'s').format('hA');*/
                        $scope.bestTime = moment(parseInt(dataObj.bestTime)).format('hA');
                    }
                    // get best and wrost city 
                    if(dataObj.wrostTime){
                       /* var duration = moment.duration(parseInt(dataObj.wrostTime)-parseInt($scope.campaignInfo.startMoment));
                        var hours = moment(duration,'s').format('hA');*/
                        $scope.wrostTime = moment(parseInt(dataObj.wrostTime)).format('hA');
                    }
                    // show rating icon
                    if($scope.ctype == 'RATING'){
                        $scope.showRatingImg = [];
                        if($scope.campaignInfo.template.disabledImage){
                            for(i=0;i<5;i++){
                                $scope.showRatingImg.push({id:i,img:$scope.campaignInfo.template.disabledImage});
                            }
                        }
                    }
                    if($scope.ctype == 'SURVEY'){
                        $scope.current = 0;
                        $scope.next = $scope.current+1;
                    }
                    // show next question
                    $scope.nextQues = function(){
                        if($scope.current < $scope.campaignInfo.template.q.length){
                            $scope.current++;
                            $scope.next = ($scope.current+1 < $scope.campaignInfo.template.q.length)? $scope.current:0;
                        }                    
                    }
                    // show previous question
                    $scope.backQues = function(){
                        if($scope.current > 0){
                            $scope.current--;
                            $scope.next = ($scope.current > 0 )? $scope.current:1;
                        }                    
                    }
                }
            });
        }
    }
}); 