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

        $scope.did = $routeParams.did; // get user information
        $scope.userAttributes = []; // user attribute array
        $scope.user = $scope.did; // set user name show at user box title
        $scope.recency = {};
        $scope.screenshotHistory = [];
        $scope.videoScreenData = {};
        $scope.interval = '';
        $scope.dotsEvents = ['TouchEvent','DoubleTapEvent','LongPressEvent'];
        $scope.showKeyboard = false;

             	//for enable/disable through app settings 
         promise = appIceService.hideDisabledFeature();
         promise.then(function(data) {
           if (data) {
             if (data[0].features.competingApps) {
                  $('#comp_int').hide();
                  $('#recency_monetry').hide();
             }else{
                 $('#comp_int').show();
                 $('#recency_monetry').show();
             }
           }
         });
         
        //  manage require api at init time
        function init() {
            $scope.getUserDetails(); // call get user detail function
        }

        $scope.addSourceToVideo = function (element, src, type) {
            var source = document.createElement('source');
            source.src = src;
            source.type = type;
            element.controls = "controls";
            //element.autoplay = "autoplay";
            element.id = "media-video";
            element.appendChild(source);
        }
        $scope.addTapToVideo = function () {
            $scope.deviceHeight = 0;
            $scope.deviceWidth = 0;

            if($scope.videoScreenData.seg && $scope.videoScreenData.seg.h && $scope.videoScreenData.seg.w){
                $scope.deviceHeight = $scope.videoScreenData.seg.h;
                $scope.deviceWidth = $scope.videoScreenData.seg.w;
            }

            var div = document.createElement('div');
            div.id = "tap";
            div.style.display = "none";
            //div.style.zIndex = 9999999;
            document.getElementById('media-player').appendChild(div);
        }

        $scope.screenVideo = function (index) {
            $('.video-overlay').show();
            $('#mp4notsupport').hide();
            $scope.interval = '';
            $scope.showKeyboard = false;
            document.getElementById('media-player').innerHTML = '';
            $scope.videoScreenData = $scope.screenshotHistory[index];
            var video = document.createElement('video');
            $scope.addSourceToVideo(video, $scope.videoScreenData.s3, 'video/mp4');
            $scope.addTapToVideo();
            video.addEventListener("playing", $scope.seekDuration, false);
            video.addEventListener("pause", $scope.onPause, false);
            video.addEventListener("seeking", $scope.seekDuration, false);
            document.getElementById('media-player').appendChild(video);
            $(".timelinetbl").removeAttr("style");
            $("#screenPlayback").modal();
            var mp4Supported = (!!document.createElement('video').canPlayType('video/mp4; codecs=avc1.42E01E,mp4a.40.2'));
             
            if(!mp4Supported){
                $('#mp4notsupport').show();
                $('.video-overlay').hide();
            }
            else{
              var interval = setInterval(function () {
                  if(document.getElementById("media-video").readyState) {
                      $('.video-overlay').hide();
                      clearInterval(interval);
                  }


              }, 100);

            }
        }

        $scope.onPause = function () {
            if ($scope.interval != '') {
                clearInterval($scope.interval);
            }
        }

        $scope.seekDuration = function () {
            if ($scope.interval != '') {
                clearInterval($scope.interval);
            }

            $scope.interval = setInterval(function () {

                var currentTime = $('#media-player').find('video').get(0).currentTime;
                var duration = $('#media-player').find('video').get(0).duration;
                 
                if ($("#timeline-" + parseInt(currentTime)).length) {
                    $(".timelinetbl").removeAttr("style");
                    $("#timeline-" + parseInt(currentTime)).css("background-color", "rgba(204, 204, 204, 0.32)");
                    // manage dot for click
                    var index = $("#timeline-" + parseInt(currentTime)).attr('data-index');
                    // validate tap event
                    if( $scope.dotsEvents.indexOf($scope.videoScreenData.mtd[index].et) >= 0){
                        var width = parseInt ( ($scope.videoScreenData.mtd[index].lx/$scope.deviceWidth) * 280);
                        var height = parseInt( ($scope.videoScreenData.mtd[index].ly/$scope.deviceHeight) * 436);
                        width = width - 10;
                        height = height - 10;
                        $("#tap").fadeIn("fast");
                        // validate tap event cordinates
                        if($scope.videoScreenData.mtd[index].lx && $scope.videoScreenData.mtd[index].ly){
                            $("#tap").animate({ 'top': height + 'px', 'left': width + 'px'}, 150);
                            setTimeout(function(){
                                $("#tap").fadeOut("slow");
                            }, 200)
                        }
                    }

                    // Manage keyboard
                    if ($scope.videoScreenData.mtd[index].et == 'KeyboardShowEvent') {
                        $scope.showKeyboard = true;
                    }

                    var nextIndex = parseInt(index)+1;

                     
                    // show and hide keyboard
                    if ($scope.videoScreenData.mtd[index].et == 'KeyboardHideEvent' || ($scope.videoScreenData.mtd[nextIndex].et == 'KeyboardHideEvent' && $("#timeline-" + parseInt(currentTime)) == $("#timeline-" + parseInt(currentTime)).next('tr').attr('id')) ) {
                    //if ($scope.videoScreenData.mtd[index].et == 'KeyboardHideEvent'){
                        $scope.showKeyboard = false;
                    }
                    $scope.$apply();
                }

                if (currentTime >= duration) {
                    clearInterval($scope.interval);
                }
            }, 1000)
        }


        //function for epoch to string time diff show 
        function secondsToString(seconds){
            var numdays = Math.floor(seconds / 86400);
            var numhours = Math.floor((seconds % 86400) / 3600);
            var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
            var numseconds = ((seconds % 86400) % 3600) % 60;
            if(numdays == 0 && numhours == 0 && numminutes == 0 && numseconds==0){
                return numseconds + " secs";
            }else if(numdays == 0 && numhours == 0 && numminutes == 0){
                return numseconds + " secs";
            }else if(numdays == 0 && numhours == 0){
                return numminutes + " mins " + numseconds + " secs";
            }else if(numdays == 0){
                return numhours + " hrs " + numminutes + " mins " + numseconds + " secs";
            }else{
                return numdays + " days " + numhours + " hrs " + numminutes + " mins " + numseconds + " secs";
            }
        }

         // user details function
        $scope.getUserDetails = function () {
            $("#activity_loader").show()
            var promise = appIceService.getUserDetails($scope.did);
            promise.then(function (data) {
                $('#overlay').hide();
                $("#activity_loader").hide()
                if (data) {
                    // store response data
                    $scope.userDetails = data.data;
                    $scope.user = $scope.userDetails.did;
                    // Recency
                    var d = new Date();
                    var currentEpoch = d.getTime();
                    var lsEpoch = $scope.userDetails.ls*1000;
                    var diff =(currentEpoch - lsEpoch);
                    diff = diff/1000;
                    diff = Math.round(diff);

                    $scope.recency.Time = secondsToString(diff);

                    if ($scope.userDetails.lsd) {
                        $scope.recency.min = parseInt($scope.userDetails.lsd / 60);
                        $scope.recency.sec = parseInt($scope.userDetails.lsd - ($scope.recency.min * 60));
                    }
                    
                    //Engagements
                    $scope.engage = 0;
                    if ($scope.userDetails.campaigns) {
                        var viewed = ($scope.userDetails.campaigns.viewed) ? $scope.userDetails.campaigns.viewed.length : 0;
                        var clicked = ($scope.userDetails.campaigns.clicked) ? $scope.userDetails.campaigns.clicked.length : 0;
                        $scope.engage = (viewed != 0) ? Math.round((clicked / viewed) * 100) + "%" : '0%';
                    }

                    // populate user attribute according key value
                    populateAttributes();

                    // last activity
                    if (data.eventlist && data.eventlist.el) {
                        var userActivity = [];
                        //$scope.userDetails.el.reverse();
                        data.eventlist.el = (data.eventlist.el.length > 0 && data.eventlist.el[0].p) ? _.sortBy(data.eventlist.el, 't') : _.sortBy(data.eventlist.el, 't');
                        data.eventlist.el.reverse();
                        // travel activity data for prepare timeline graph at ui
                        data.eventlist.el.forEach(function (activity) {
                            userActivity.push({
                                time: moment(activity.t * 1000).format('MM/DD/YY H:mm:ss'), // convert seconds into date time formate throught moment
                                color: '#555',
                                content: populateTimelineDetail(activity) // get user activity content with segments
                            });
                        });
                        $("#recentActivity").timeline({ data: userActivity });
                    }
                }
            })
            .catch(function(error){
                $('#overlay').hide();
            });
        }

        // populute user attribute at view
        function populateAttributes() {
            $scope.userAttributes = [];
            if ($scope.userDetails._custom_FName) {
                $scope.userAttributes.push({ name: 'FName', value: $scope.userDetails._custom_FName })
            }
            if ($scope.userDetails._custom_LName) {
                $scope.userAttributes.push({ name: 'LName', value: $scope.userDetails._custom_LName })
            }
            if ($scope.userDetails._custom_Mobile) {
                $scope.userAttributes.push({ name: 'Mobile', value: $scope.userDetails._custom_Mobile })
            }
            if ($scope.userDetails._custom_Email) {
                $scope.userAttributes.push({ name: 'Email', value: $scope.userDetails._custom_Email })
            }
            if ($scope.userDetails._custom_City) {
                $scope.userAttributes.push({ name: 'City', value: $scope.userDetails._custom_City })
            }
            if ($scope.userDetails._custom_Gender) {
                $scope.userAttributes.push({ name: 'Gender', value: $scope.userDetails._custom_Gender })
            }
            if ($scope.userDetails._custom_Age) {
                $scope.userAttributes.push({ name: 'Age', value: $scope.userDetails._custom_Age })
            }
            if ($scope.userDetails._custom_Profession) {
                $scope.userAttributes.push({ name: 'Profession', value: $scope.userDetails._custom_Profession })
            }
            if ($scope.userDetails.d) {
                $scope.userAttributes.push({ name: 'Model', value: $scope.userDetails.d })
            }
            if ($scope.userDetails.c) {
                $scope.userAttributes.push({ name: 'Carrier', value: $scope.userDetails.c })
            }
            if ($scope.userDetails.av || $scope.userDetails._app_version) {
                $scope.userAttributes.push({ name: 'App Version', value: $scope.userDetails.av?$scope.userDetails.av:$scope.userDetails._app_version})
            }
            if ($scope.userDetails.ci) {
                $scope.userAttributes.push({ name: 'Customer ID', value: $scope.userDetails.ci })
            }

            // travel user details object for find _custom__ keyword
            // angular.forEach($scope.userDetails, function(value, key) {
            //     // find _custom_ it will return position of this string
            //     if( key.indexOf('_custom_') != -1 ){
            //         key = key.replace('_custom_',''); // replace _custom_ string with blank
            //         this.push({name: key, value: value}); // push into userAttributes array
            //     }
            // }, $scope.userAttributes);
        }

        // get user recent activity
        $scope.getUserRecentActivity = function (did) {
            var promise = appIceService.getUserRecentActivity(did);
            promise.then(function (data) {
                if (data) {
                    var userActivity = [];
                    // travel activity data for prepare timeline graph at ui
                    data.forEach(function (activity) {
                        userActivity.push({
                            time: moment.utc(activity.eventTime * 1000).format('MM/DD/YY H:m:s'), // convert seconds into date time formate throught moment
                            color: '#555',
                            content: populateTimelineDetail(activity) // get user activity content with segments
                        });
                    });

                    $("#recentActivity").timeline({ data: userActivity });
                }
            });
        }

        // populate user timeline detils at right side
        function populateTimelineDetail(activity) {
            var content = '<strong>' + activity.k + '</strong> <br />';

            if (activity.segment != undefined) {
                // travel segement object
                angular.forEach(activity.segment, function (value, key) {
                    // check value type object then skip that key value
                    if (typeof value !== "object") {
                        if (key == 'updatedAt' || key == 'createdAt')
                            value = moment(value * 1000).format("DD/MM/YYYY");

                        content += key + " : " + value + " <br />";
                    }
                });
            }

            return content;
        }

        init(); // call init function for get user information
    });
