crmApp.controller('MenuController', MenuController);

function MenuController($scope, $location, $window, MenuBarService, TaxPayerService, $timeout, uiCalendarConfig, TaskSI, GeneralSI, $interval, localStorageService) {
    var vm = this;
    vm.MB = MenuBarService.MB;
    vm.TP = TaxPayerService.TP;
    $scope.menuToggle = false;
    $scope.sideBarToggle = false;
    $scope.notiToggle = false;
    $scope.inbToggle = false;
    $scope.calendarToggle = false;
    var oriWindowTitle = $window.document.title;
    var counter = 0;
    var timer;
    $scope.isSidebarOpened = false;

    //if (localStorage.getItem("crmApp.UserInfo") === null) {
    //    TaskSI.getLoginInfo().then(function (r) {
    //        if (r.status === 200) {
    //            vm.loginResponse = r.data;
    //            localStorageService.clearAll();
    //            localStorageService.set('UserInfo', vm.loginResponse);
    //            $scope.UserInfo = localStorageService.get('UserInfo');
    //        }
    //    });
    //} else {
    //    $scope.UserInfo = localStorageService.get('UserInfo');
    //    console.log($scope.UserInfo);
    //}

    vm.UserName = "Eric Yap";
    vm.UserTitle = "Agent";
    vm.UserInitials = "EY";
    vm.Cawangan = "Cawangan Bangi";
    vm.Area = "HCL";

    vm.Channel = $window.channel;
    vm.ScenarioID = $window.scenarioID;
    vm.CaseID = $window.caseid;
    vm.TaxPayerID = $window.taxpayerid;

    $scope.$on("ToggleSidebar", function (e, val) {
        $scope.isSidebarOpened = val;
        e.stopPropagation();
    });

    $scope.ToggleMenu = function () {
        $scope.notiToggle = false;
        $scope.calendarToggle = false;
        $scope.menuToggle = !$scope.menuToggle;
    };

    $scope.ToggleNotification = function () {
        $scope.menuToggle = false;
        $scope.calendarToggle = false;
        $scope.notiToggle = !$scope.notiToggle;
    };

    $scope.ToggleCalender = function (calendar) {
        $scope.menuToggle = false;
        $scope.notiToggle = false;
        if (!$scope.calendarToggle) {
            loadCalendar();
        }
        else {
            $scope.calendarToggle = !$scope.calendarToggle;
        }
    };

    $scope.ReadAlertList = function (isRead, TaskAlertID,Url) {
        if (!isRead) {
            var data = {
                IsContentRead: true,
                TaskAlertID: TaskAlertID,
            }

            GeneralSI.updatedCurrentContent(data).then(function (r) {
                //if (r.data != null)
                //{
                //    vm.redirectTo(r.data.URL); //py: comment it for open new tab, not redirect
                //}
            
            }, function (err) {
                console.log(err);
            });
        }
        //else
        //{
        //    vm.redirectTo(Url);  //py: comment it for open new tab, not redirect
        //}

    };

    $scope.ReadLatestAlert = function () {
        getDataforDashboardNotification()
    }

    //$scope.$watch('menu.TP.Name', function () {
    //    switch (vm.MB.ActChannelID) {
    //        case 1:  //Chat
    //            vm.ChannelDetails = vm.TP.Name ? vm.TP.Name : '';
    //            break;
    //        case 7:  //CFF
    //            vm.ChannelDetails = vm.TP.Name ? vm.TP.Name : '';
    //            break;
    //        case 8:  //Social media
    //            vm.ChannelDetails = vm.TP.Name ? vm.TP.Name : '';
    //            break;
    //    }
    //});

    //$scope.$watchGroup(['menu.MB.ActChannelID', 'menu.MB.Aliran'], function () {
    //    $timeout.cancel(timer);
    //    $window.document.title = oriWindowTitle;
    //    if (vm.MB.ActChannelID == 1 || vm.MB.ActChannelID == 5 || vm.MB.ActChannelID == 7 || vm.MB.ActChannelID == 8) {
    //        $timeout(onTimeout, 2000);
    //    }

    //    switch (vm.MB.ActChannelID) {
    //        case 1:  //Chat
    //            vm.ChannelTitle = 'Chat';
    //            vm.SubMenuIcon = 'fa fa-weixin text-blue';
    //            vm.MenuIcon = 'fa fa-commenting';
    //            vm.ChannelDetails = vm.TP.Name ? vm.TP.Name : '';
    //            vm.ChannelIndicator = 'ql-item noti-link';
    //            changeFavicon('/Content/images/comment.png');
    //            break;
    //        case 5: //Phone 
    //            if (vm.MB.Aliran && vm.MB.Aliran.toUpperCase() == 'OUT') {
    //                vm.ChannelTitle = 'Call';
    //                vm.SubMenuIcon = 'fa fa-phone text-orange';
    //                vm.ChannelIndicator = 'ql-item noti-link out-call';
    //                changeFavicon('/Content/images/phone-outbound.png');
    //            }
    //            else {
    //                vm.ChannelTitle = 'Call';
    //                vm.SubMenuIcon = 'fa fa-phone text-green';
    //                vm.ChannelIndicator = 'ql-item noti-link inb-call';
    //                changeFavicon('/Content/images/phone-inbound.png');
    //            }
    //            vm.MenuIcon = 'fa fa-volume-control-phone';
    //            vm.ChannelDetails = vm.MB.TelNoInteraksi ? vm.MB.TelNoInteraksi : '';
    //            break;
    //        case 7:
    //            vm.ChannelTitle = 'Social Media';
    //            vm.SubMenuIcon = 'fa fa-envelope';
    //            vm.MenuIcon = 'fa fa-share-alt';
    //            vm.ChannelDetails = vm.TP.Name ? vm.TP.Name : '';
    //            vm.ChannelIndicator = 'ql-item noti-link';
    //            changeFavicon('/Content/images/email.png');
    //            break;
    //        case 8:
    //            vm.ChannelTitle = 'CFF';
    //            vm.SubMenuIcon = 'fa fa-envelope text-yellow';
    //            vm.MenuIcon = 'fa fa-envelope';
    //            vm.ChannelDetails = vm.TP.Name ? vm.TP.Name : '';
    //            vm.ChannelIndicator = 'ql-item noti-link';
    //            changeFavicon('/Content/images/email.png');
    //            break;
    //        default:
    //            vm.ChannelTitle = '';
    //            vm.SubMenuIcon = '';
    //            vm.MenuIcon = '';
    //            vm.ChannelDetails = '';
    //            vm.ChannelIndicator = '';
    //            changeFavicon("/Content/images/logolhdn.png");
    //            break;
    //    }

    //});

    function onTimeout() {

        counter++;
        if (counter % 2 == 0) {
            $window.document.title = vm.ChannelDetails ? "..." + vm.ChannelDetails : oriWindowTitle;
        } else {
            $window.document.title = vm.ChannelTitle + "...";
        }
        timer = $timeout(onTimeout, 2000);

    }

    function changeFavicon(src) {
        var link = document.createElement('link'),
            oldLink = document.getElementById('dynamic-favicon');
        link.id = 'dynamic-favicon';
        link.rel = 'shortcut icon';
        link.href = src;
        if (oldLink) {
            document.head.removeChild(oldLink);
        }
        document.head.appendChild(link);
    }

    vm.onNewActivity = function ($event) {
        $event.preventDefault();
        angular.element('#btn-submit2').click();
    }

    vm.redirectTo = function (url) {

        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }

    vm.onNewSegmentise = function ($event) {
        $event.preventDefault();
        angular.element('#btn-submitseg').click();
    }

    vm.onNewEmailBlastSegmentise = function ($event) {
        $event.preventDefault();
        angular.element('#btn-submitemailblastseg').click();
    }

    vm.onNewTask = function ($event) {
        $event.preventDefault();
        angular.element('#btn-submittask').click();
    }

    vm.init = function () {

        getDataforDashboardNotification()

        //Internal 1 min to get latest data from db
        //$interval(getDataforDashboardNotification, 60000);

        vm.GetNotificationList = function () {
            vm.redirectTo("/Home/Notification");
        }
    }

    function getDataforDashboardNotification() {
        var data = {
            IsSeeFullList: false
        }

        GeneralSI.getMyDashboardNotifcation(data).then(function (r) {
            if (r.status == 200) {
                vm.totalNotification = r.data.TotalNotification;
                vm.TaskListAlert = r.data.TaskListAlert;
                if (vm.totalNotification == 0 || vm.totalNotification == null) {
                    vm.NoAlertNotification = true;
                }
            }
        }, function (err) {
            console.log(err);
        });

    }

    // Moved load calander data into functions
    // To render calendar on click only
    $scope.ShowCalendar = function (calendar) {
        loadCalendar();
        //if (uiCalendarConfig.calendars[calendar]) {
        //    uiCalendarConfig.calendars[calendar].fullCalendar('render');
        //}
        //uiCalendarConfig.calendars['my_calendar'].fullCalendar('render');
        //if ($scope.calendarToggle) renderFullCalendar();
    }

    function renderFullCalendar() {

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        //displayCalendar();

        $scope.events = {
            //color: '#00f',
            textColor: '#FFF',
            events: $scope.myevents
        };
        console.log('events', [$scope.events]);

        /* alert on eventClick */
        $scope.alertOnEventClick = function (event, jsEvent, view) {

            // if(date.links != undefined && date.links !='')
            // window.open(date.links,'_blank');
            // alert(date.title);
            // $('#modalTitle').html(date.title);
            // $('#modalBody').html(date.description);
            // $('#eventUrl').attr('href',date.links);
            // $('#fullCalModal').modal();

            // vm.openDialog(e, '#fullCalModal');
        	if (event.taskurl)
        	{
        		window.open(event.taskurl);
        		return false;
        	}

            $('#fullCalModal').modal();
        };
        /* alert on Drop */
        $scope.alertOnDrop = function (event, delta, revertFunc, jsEvent, ui, view) {
            console.log('event', event);
            console.log('view', view);
            $scope.alertMessage = ('Event Droped to make ' + delta._days + 'day delta and ' + delta._months + ' month delta');
            if (event.editable === false)
                revertFunc();
        };
        /* alert on Resize */
        $scope.alertOnResize = function (event, delta, revertFunc, jsEvent, ui, view) {
            console.log('event', event);
            console.log('view', view);
            $scope.alertMessage = ('Event Droped to make ' + delta._days + 'day delta and ' + delta._months + ' month delta');
            if (event.editable === false)
                revertFunc();
        };
        /* add and removes an event source of choice */
        $scope.addRemoveEventSource = function (sources, source) {
            var canAdd = 0;
            angular.forEach(sources, function (value, key) {
                if (sources[key] === source) {
                    sources.splice(key, 1);
                    canAdd = 1;
                }
            });
            if (canAdd === 0) {
                sources.push(source);
            }
        };
        /* add custom event*/
        $scope.addEvent = function () {
            $scope.events.push({
                title: 'Open Sesame',
                start: new Date(y, m, 28),
                end: new Date(y, m, 29),
                className: ['openSesame']
            });
        };
        /* remove event */
        $scope.remove = function (index) {
            $scope.events.splice(index, 1);
        };
        /* Change View */
        $scope.changeView = function (view, calendar) {
            uiCalendarConfig.calendars[calendar].fullCalendar('changeView', view);
        };
        /* Change View */
        $scope.renderCalender = function (calendar) {

            if (uiCalendarConfig.calendars[calendar]) {
                uiCalendarConfig.calendars[calendar].fullCalendar('render');
            }
        };

        /* Render Tooltip */
        $scope.eventRender = function (event, element, view) {
            // element.attr({
            // // 'tooltip': event.title + '<br/>' + event.username,
            // // 'tooltip-append-to-body': true
            // 'tooltip-placement' : 'top', 
            // 'uib-tooltip': event.title, 
            // });
            // $compile(element)($scope);  // element.attr({
            // // 'tooltip': event.title + '<br/>' + event.username,
            // // 'tooltip-append-to-body': true
            // 'tooltip-placement' : 'top', 
            // 'uib-tooltip': event.title, 
            // });
            // $compile(element)($scope);
            //element.attr('href', 'javascript:void(0);');
            // element.click(function() {
            // $('#modaltitle').html(event.title);
            // $('#modalbody').html(event.description);
            // $('#eventurl').attr('href',event.url);
            // $('#fullcalmodal').modal();
            // });


            // $('#modalTitle').html(event.title);
            // $('#modalBody').html(event.description);
            // $('#eventUrl').attr('href',event.links);

        };
        /* config object */
        $scope.uiConfig = {
            calendar: {
                selectable: false,
                editable: true,
                eventLimit: true, // allow "more" link when too many events
                height: 450,
                header: {
                    left: 'title',
                    center: '',
                    right: 'prev,today,next agendaDay,agendaWeek,month' //button arrangement 
                },
                //Change button label
                buttonText: {
                    today: "Hari ini",
                    month: "BULAN", week: "MINGGU", day: "HARI"
                },
                eventClick: $scope.alertOnEventClick,


                eventDrop: $scope.alertOnDrop,
                eventResize: $scope.alertOnResize,
                eventRender: $scope.eventRender,
                timeFormat: '',
                //displayEventTime: false,
            }
        };
        /* event sources array*/
        $scope.eventSources = [$scope.events];

        console.log(' $scope.eventSources', $scope.eventSources);
        $scope.calendarToggle = !$scope.calendarToggle;
        //uiCalendarConfig.calendars['my_calendar'].fullCalendar('my_calendar');
    };

    function loadCalendar() {
        $scope.myevents = [];
        // Load calendar lastest data only when open
        if (!$scope.calendarToggle) {
            TaskSI.getTaskForCalendar().then(function (r) {
                if (r.status === 200) {
                    var events = [];
                    angular.forEach(r.data, function (event, key) {
                    	dt = new Date(event.DueDate);
                    	dt.setHours(dt.getHours() + 9);
                        $scope.myevents.push({
                            id: event.TaskID,
                            title: event.title,
                            description: event.Description,
                            start: new Date(event.StartDate),
                            end: new Date(dt),
                            taskurl: '/task/detail/' + event.TaskID,
                            //color: event.Status == 'O
                            color: calendarEventColor(event.Status),
							status: event.Status
                        });
                    });

                    console.log('DB Calendar', $scope.myevents);
                    if (!$scope.calendarToggle) renderFullCalendar();
                };
            });
        }
        else { $scope.calendarToggle = !$scope.calendarToggle } //Close Calendar

        // };


    }

    function calendarEventColor(status) {

    	if (status == 'Open')
    	{
    		var colorCode = '#ad2121';
    	}
		
    	if (status == 'Completed')
    	{
    		var colorCode = '#4CAF50';
    	}
    	
    	if (status == 'Inactive')
    	{
    		var colorCode = '#D3D3D3';
    	}
			
    	if (status == 'PTP')
    	{
    		var colorCode = '#FFA500';
    	}
			

        return colorCode
    };

    vm.SelectNoPengenalan = function () {
        var IDNo = vm.IDNo;
        if (!vm.IDNo) {
            swal("Gagal!", "Sila isi No.K.P. Baru.", "error");
            return;
        }
        angular.element('#IDNo').val(IDNo);
        var form = angular.element('#DashboardSearchNoPengenalan');
        form.submit();
    }
}