define("ticketChartsControllers", ["SHARED/jquery", "SHARED/juzu-ajax"], function ($, jz) {
    var ticketChartsCtrl = function ($scope, $q, $timeout, $http, $filter) {
        var ticketChartsContainer = $('#ticketCharts');
        var deferred = $q.defer();
		 $scope.allSpaces = {
			groupId: "all",
			name: "All"
		};
        $scope.selectedSpace = $scope.allSpaces;
        $scope.spaces=[];
        $scope.showGraphs = false;
        $scope.showSpaces = false;
        $scope.showSpaceCharts = true;
        $scope.showAllCustomerCharts = false;
        $scope.assignees=[];
		$scope.showGetAll=false;

        $scope.customerSatisfactionPrc = null;
        $scope.firstTimeResponceAverage = null;
        $scope.timeToResolutionAverage = null;

		 $scope.openTab = function (tabName) {

            $("#charts").css("display", "none");
            $("#trends").css("display", "none");

            $("#chartsTab").removeClass("active");
            $("#trendsTab").removeClass("active");

            $("#" + tabName).css("display", "block");
            $("#" + tabName + "Tab").addClass("active");
        }
		
		$scope.timeMetricslinePeriod="weekly";
		$scope.openVSClosedLinePeriod="weekly";
		$scope.logbyStatusChartPeriod="weekly";
		$scope.satisfactionLinePeriod="weekly";
		$scope.openVSClosedLineType="charge";
		
		$scope.getTimeMetricsChart = function () {
			if($scope.timeMetricslinePeriod=="monthly"){
				$scope.getTimeMetricsByMonthChart();
			}else{
				$scope.getTimeMetricsByWeekChart();
			}
		}

		
		$scope.getSatisfactionChart = function () {
			if($scope.satisfactionLinePeriod=="monthly"){
				$scope.getSatisfactionByMonthChart();
			}else{
				$scope.getSatisfactionByWeekChart();
			}
		}



		$scope.startDate=0;
		$scope.endDate=(new Date()).getTime();


                  var lessThan3Day = new Date();
                  lessThan3Day.setDate(lessThan3Day.getDate() - 2);
                  $scope.customTemplates = [
                    {
                      name: 'Last 3 Days',
                      dateStart: lessThan3Day,
                      dateEnd: new Date(),
                    }
                  ];
                  $scope.calendarModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.pickerModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.advancedModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.serviceModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.selectedDate = {};
                  $scope.selectedDates = [];
                  $scope.selectDateRange = function ($event, autoConfirm) {
                    $mdDateRangePicker.show({
                      model: $scope.serviceModel,
                      autoConfirm: autoConfirm,
                      targetEvent: $event,
                      customTemplates: $scope.customTemplates,
                    }).then(function (result) {
                      Object.assign($scope.serviceModel, result);
                    }).catch(function () {
                      console.log('Cancelled');
                    });
                  }
                  $scope.format = function (dateStart, dateEnd, template, templateName) {
                    return template ? 'Range of ' + (templateName || template) : (dateStart && dateEnd && (dateStart.toLocaleDateString() + ' to ' + dateEnd.toLocaleDateString()));
                  }
                  $scope.isDisabledDate = function (d) {
                    return d.getDay() === 0 || d.getDay() === 6;
                  }


        $scope.setRange = function (dates) {
			$scope.showGetAll=true;
			$scope.startDate=dates[0].getTime();
			$scope.endDate=dates[dates.length-1].getTime();
			$scope.getMetricsByDates();
			$scope.getCustomerOpenVsClosedTicketsByDates();
            $scope.getTicketsByStatusAndDatesChartData();
			$scope.getCustomersTicketsByAssigneeChartData();
			$scope.getCustomersTicketsBySeverityChartData();
            $scope.getOpenVSClosedLineChartData();
            $scope.getLogbyStatusChartData();
			$scope.getTimeMetricsChart();
			$scope.getSatisfactionChart();
        }

    $scope.getDisplayName = function(username){
      for (var i = 0; i < $scope.assignees.length; i++) {
        if ($scope.assignees[i].userName === username) {
           return $scope.assignees[i].displayName;
        }
      }
      return $scope.i18n.empty;
    }

        $scope.loadAssignees = function() {
           $http({
              method: 'GET',
              url : ticketChartsContainer.jzURL('TicketChartsController.getSupportUsernames')
           }).then(function successCallback(data) {
               $scope.assignees = data.data;
               $timeout(function() {
                 //   $scope.setResultMessage("", "info")
               }, 3000);
           },function errorCallback(data) {
               $scope.setResultMessage(data, "error");
           });
        }


        $scope.hideClvsOpSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.lineClvsOpChartObject.view.columns[col] == col) {
                    $scope.lineClvsOpChartObject.view.columns[col] = {
                        label: $scope.lineClvsOpChartObject.data.cols[col].label,
                        type: $scope.lineClvsOpChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.lineClvsOpChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.lineClvsOpChartObject.view.columns[col] = col;
                    $scope.lineClvsOpChartObject.options.colors[col - 1] = $scope.lineClvsOpChartObject.options.defaultColors[col - 1];
                }
            }
        }
        $scope.testclvsop = function (selectedItem) {
            var col = selectedItem.column;

        }

        $scope.lineClvsOpChartObject = {};
        $scope.lineClvsOpChartObject.type = "LineChart";
        $scope.lineClvsOpChartObject.displayed = false;


        $scope.lineClvsOpChartObject.options = {
            "colors": ['#4285f4', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },
			"title": 'Tickets Closed Vs Opened Trend',
            "defaultColors": ['#4285f4', '#db4437'],
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',
            "height": 450
        };
        $scope.lineClvsOpChartObject.view = {
            columns: [0, 1, 2]
        };





        $scope.hideLogbyStatusSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.lineLogbyStatusChartObject.view.columns[col] == col) {
                    $scope.lineLogbyStatusChartObject.view.columns[col] = {
                        label: $scope.lineLogbyStatusChartObject.data.cols[col].label,
                        type: $scope.lineLogbyStatusChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.lineLogbyStatusChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.lineLogbyStatusChartObject.view.columns[col] = col;
                    $scope.lineLogbyStatusChartObject.options.colors[col - 1] = $scope.lineLogbyStatusChartObject.options.defaultColors[col - 1];
                }
            }
        }

        $scope.lineLogbyStatusChartObject = {};
        $scope.lineLogbyStatusChartObject.type = "LineChart";
        $scope.lineLogbyStatusChartObject.displayed = false;


        $scope.lineLogbyStatusChartObject.options = {
			"title": 'Tickets Status Trend',
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',
            "height": 450
        };
        $scope.lineLogbyStatusChartObject.view = {
            columns: [0, 1, 2, 3,4,5]
        };


        $scope.pieChartSpaceByStatusObject = {};
        $scope.pieChartSpaceByStatusObject.options = {
            pieHole: 0.3,
            title: 'Space tickets by status',
			height: 450
        };
        $scope.pieChartSpaceByStatusObject.type = "ColumnChart";

        $scope.pieChartSpaceByOwnerObject = {};
        $scope.pieChartSpaceByOwnerObject.options = {
            pieHole: 0.3,
            title: 'Space tickets by Third party',
            width:817,height:500
        };
        $scope.pieChartSpaceByOwnerObject.type = "PieChart";

        $scope.pieChartSpaceByAssigneeObject = {};
        $scope.pieChartSpaceByAssigneeObject.options = {
            pieHole: 0.3,
            title: 'Space tickets by Assignee',
            width:817,height:500
        };
        $scope.pieChartSpaceByAssigneeObject.type = "PieChart";



        $scope.pieChartByAssigneeObject = {};
        $scope.pieChartByAssigneeObject.options = {
            pieHole: 0.3,
            title: 'Customers tickets by Assignee',
            width:817,height:500
        };
        $scope.pieChartByAssigneeObject.type = "PieChart";


        $scope.pieChartBySeverityObject = {};
        $scope.pieChartBySeverityObject.options = {
            pieHole: 0.3,
            title: 'Customers tickets by Severity',
            width:817,height:500
        };
        $scope.pieChartBySeverityObject.type = "PieChart";



        $scope.pieChartBySpaceObject = {};
        $scope.pieChartBySpaceObject.options = {
            pieHole: 0.3,
            title: 'All customer tickets by space',
            width:817,height:500
        };
        $scope.pieChartBySpaceObject.type = "PieChart";

        $scope.pieChartByOwnerObject = {};
        $scope.pieChartByOwnerObject.options = {
            pieHole: 0.3,
            title: 'All customer tickets by owner',
            width:817,height:500
        };
        $scope.pieChartByOwnerObject.type = "PieChart";

        $scope.pieChartByStatusObject = {};
        $scope.pieChartByStatusObject.options = {
            pieHole: 0.3,
			width:817,
			height:500,
            title: 'All customer tickets by status'
        };
        $scope.pieChartByStatusObject.type = "ColumnChart";


        $scope.pieChartClosedVsOpenedObject = {};
        $scope.pieChartClosedVsOpenedObject.options = {
            pieHole: 0.3,
            title: 'Closed VS Opened Customer tickets',
            width:817,height:500
        };
        $scope.pieChartClosedVsOpenedObject.type = "PieChart";


                $scope.columnChartBySpaceObject = {};
                $scope.columnChartBySpaceObject.options = {
                title: 'All customer tickets by space',
				width:817,
                height:500,
                };
                $scope.columnChartBySpaceObject.type = "BarChart";


        $scope.timeMetricslineChartObject = {};
        $scope.timeMetricslineChartObject.type = "LineChart";
        $scope.timeMetricslineChartObject.displayed = false;


        $scope.timeMetricslineChartObject.options = {
            "colors": ['#4285f4', '#00b36b', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },
			"title": 'Time Metrics Trend',
            "defaultColors": ['#4285f4', '#00b36b', '#db4437'],
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',
            "height": 450,
            "vAxis": {
                "title": "",
				"color": 'red',
				"textStyle": {
                                "color": 'transparent'
                            },

            }
        };
        $scope.timeMetricslineChartObject.view = {
            columns: [0, 1, 2]
        };




        $scope.hideTimeToFirstResponseSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.timeMetricslineChartObject.view.columns[col] == col) {
                    $scope.timeMetricslineChartObject.view.columns[col] = {
                        label: $scope.timeMetricslineChartObject.data.cols[col].label,
                        type: $scope.timeMetricslineChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.timeMetricslineChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.timeMetricslineChartObject.view.columns[col] = col;
                    $scope.timeMetricslineChartObject.options.colors[col - 1] = $scope.timeMetricslineChartObject.options.defaultColors[col - 1];
                }
            }
        }


        $scope.cSatlineChartObject = {};
        $scope.cSatlineChartObject.type = "LineChart";
        $scope.cSatlineChartObject.displayed = false;


        $scope.cSatlineChartObject.options = {
            "colors": ['#4285f4', '#00b36b', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },
			"title": 'Customer satisfaction Trend',
            "defaultColors": ['#4285f4', '#00b36b', '#db4437'],
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',
            "height": 450
        };
        $scope.cSatlineChartObject.view = {
            columns: [0, 1, 2]
        };




        $scope.hideSatisfactionSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.cSatlineChartObject.view.columns[col] == col) {
                    $scope.cSatlineChartObject.view.columns[col] = {
                        label: $scope.cSatlineChartObject.data.cols[col].label,
                        type: $scope.cSatlineChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.cSatlineChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.cSatlineChartObject.view.columns[col] = col;
                    $scope.cSatlineChartObject.options.colors[col - 1] = $scope.timeMetricslineChartObject.options.defaultColors[col - 1];
                }
            }
        }

        $scope.setResultMessage = function (text, type) {
            $scope.resultMessageClass = "alert-" + type;
            $scope.resultMessageClassExt = "uiIcon" + type.charAt(0).toUpperCase()+ type.slice(1);
            $scope.showAlert = true;
            $scope.resultMessage = text;
        }


        $scope.loadBundle = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getBundle') + "&locale=" + eXo.env.portal.language
            }).then(function successCallback(data) {
                $scope.i18n = data.data;
                deferred.resolve(data);
                /*$scope.setResultMessage(data, "success");*/
                $scope.showAlert = false;
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }





                $scope.getSpaceTicketsByAssigneeChartData = function (spaceId) {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.countSpaceTicketsGroupdByAssignee')+ "&spaceId="+spaceId
                    }).then(function successCallback(data) {
                        ticketsNumberByAssigneeList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < ticketsNumberByAssigneeList.length; i++) {
                                     var obj = ticketsNumberByAssigneeList[i];
                                              ticketsArray.push({ c: [{v:  $scope.getDisplayName(obj.assignee)}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartSpaceByAssigneeObject.data = {"cols": [
                                {id: "t", label: "Assignee", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }





                $scope.getSpaceTicketsByStatusChartData = function (spaceId) {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.countSpaceTicketsGroupdByStatus')+ "&spaceId="+spaceId
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartSpaceByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }




                $scope.getSpaceTicketsByOwnerChartData = function (spaceId) {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.countSpaceTicketsGroupdByOwner')+ "&spaceId="+spaceId
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: obj.owner}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartSpaceByOwnerObject.data = {"cols": [
                                {id: "t", label: "Owner", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getTicketsBySpaceChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdBySpace')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberBySpaceList = data.data;


                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberBySpaceList.length; i++) {
                                     var obj = $scope.ticketsNumberBySpaceList[i];
                                              ticketsArray.push({ c: [{v: obj.space}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartBySpaceObject.data = {"cols": [
                                {id: "t", label: "Space", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };
                            $scope.columnChartBySpaceObject.data = {"cols": [
                                {id: "t", label: "Space", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


                $scope.getTicketsByOwnerChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByOwner')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByOwnerList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByOwnerList.length; i++) {
                                     var obj = $scope.ticketsNumberByOwnerList[i];
                                              ticketsArray.push({ c: [{v: obj.owner}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByOwnerObject.data = {"cols": [
                                {id: "t", label: "Owner", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getTicketsByStatusChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByStatus')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getCustomerOpenVsClosedTickets = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerOpenVsClosedTickets')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberClosedVsOpenedList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberClosedVsOpenedList.length; i++) {
                                     var obj = $scope.ticketsNumberClosedVsOpenedList[i];
                                              ticketsArray.push({ c: [{v: obj.status}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartClosedVsOpenedObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


                 $scope.getCustomerOpenVsClosedTicketsByDates = function () {
                     $http({
                         method: 'GET',
                         url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerOpenVsClosedTicketsByDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                     }).then(function successCallback(data) {
                         $scope.ticketsNumberClosedVsOpenedList = data.data;

                               var ticketsArray = [];
                                 for(var i = 0; i < $scope.ticketsNumberClosedVsOpenedList.length; i++) {
                                      var obj = $scope.ticketsNumberClosedVsOpenedList[i];
                                               ticketsArray.push({ c: [{v: obj.status}, {v: obj.ticketNumber}]});
                                          }
                             $scope.pieChartClosedVsOpenedObject.data = {"cols": [
                                 {id: "t", label: "Status", type: "string"},
                                 {id: "s", label: "Tickets", type: "number"}
                             ], "rows":  ticketsArray
                             };

                         deferred.resolve(data);
                     }, function errorCallback(data) {
                         $scope.setResultMessage($scope.i18n.defaultError, "error");
                     });
                 }

				 
				 

                $scope.getTicketsByStatusAndDatesChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByStatusAndDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }



                $scope.getCustomersTicketsByAssigneeChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByAssignee')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                        ticketsNumberByAssigneeList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < ticketsNumberByAssigneeList.length; i++) {
                                     var obj = ticketsNumberByAssigneeList[i];
                                              ticketsArray.push({ c: [{v:  $scope.getDisplayName(obj.assignee)}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByAssigneeObject.data = {"cols": [
                                {id: "t", label: "Assignee", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }



                $scope.getCustomersTicketsBySeverityChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdBySeverity')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                        ticketsNumberBySeverityList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < ticketsNumberBySeverityList.length; i++) {
                                     var obj = ticketsNumberBySeverityList[i];
                                              ticketsArray.push({ c: [{v:  $scope.i18n[obj.severity]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartBySeverityObject.data = {"cols": [
                                {id: "t", label: "severity", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }




        $scope.getSpaceMetrics = function (currentSpace) {

            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSpaceMetricsData')+ "&currentSpace=" + currentSpace
            }).then(function successCallback(data) {
                d = data.data;
                $scope.customerTotalVotes = d.customerTotalVotes ;
                $scope.customerSatisfactionPrc = d.customerSatisfactionPrc ;
                $scope.firstTimeResponceAverage = convertMS(d.firstTimeResponceAverage);
                $scope.timeToResolutionAverage = convertMS(d.timeToResolutionAverage);
                $scope.showSpaceCharts = true;
                $scope.showAllCustomerCharts = false;
                $scope.getSpaceTicketsByAssigneeChartData(d.currentSpace);
                $scope.getSpaceTicketsByStatusChartData(d.currentSpace);
                $scope.getSpaceTicketsByOwnerChartData(d.currentSpace);
                deferred.resolve(data);
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }


        $scope.getMetricsByDates = function () {

            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getMetricsByDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
            }).then(function successCallback(data) {
                d = data.data;
                $scope.customerTotalVotes = d.customerTotalVotes ;
                $scope.customerSatisfactionPrc = d.customerSatisfactionPrc ;
                $scope.firstTimeResponceAverage = convertMS(d.firstTimeResponceAverage);
                $scope.timeToResolutionAverage = convertMS(d.timeToResolutionAverage);
                deferred.resolve(data);
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }


                $scope.loadData = function () {
        			if ($scope.showGetAll==false){
        				$scope.startDate=0;
        			}
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getData')
                    }).then(function successCallback(data) {
                        d = data.data;
                        $scope.customerTotalVotes = d.customerTotalVotes ;
                        $scope.customerSatisfactionPrc = d.customerSatisfactionPrc ;
                        $scope.firstTimeResponceAverage = convertMS(d.firstTimeResponceAverage);
                        $scope.timeToResolutionAverage = convertMS(d.timeToResolutionAverage);
                        if(d.currentSpace==null){
                         $scope.loadSpaces();
                         $scope.showSpaces = true;
                         $scope.showSpaceCharts = false;
                         $scope.showAllCustomerCharts = true;
                         $scope.getTicketsBySpaceChartData();
                         $scope.getTicketsByOwnerChartData();
                         $scope.getTicketsByStatusChartData();
                         $scope.getCustomerOpenVsClosedTickets();
						 $scope.getCustomersTicketsByAssigneeChartData();
						 $scope.getCustomersTicketsBySeverityChartData();
                         $scope.getOpenVSClosedLineChartData();
        				 $scope.getLogbyStatusChartData();
						 $scope.getTimeMetricsChart();
						 $scope.getSatisfactionChart();
						 
                        }else{
                         $scope.showSpaceCharts = true;
                         $scope.showAllCustomerCharts = false;
                         $scope.getSpaceTicketsByAssigneeChartData(d.currentSpace);
                         $scope.getSpaceTicketsByStatusChartData(d.currentSpace);
                         $scope.getSpaceTicketsByOwnerChartData(d.currentSpace);
                        }
                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

		 $scope.getAll = function() {
			 $scope.pickerModel = {
                    selectedTemplateName:'',
                };
            $scope.showGetAll=false;
        	$scope.startDate=0;
        	$scope.endDate=(new Date()).getTime();
            $scope.loadData();
        };


        function convertMS( milliseconds ) {
            var day, hour, minute, seconds;
            seconds = Math.floor(milliseconds / 1000);
            minute = Math.floor(seconds / 60);
            seconds = seconds % 60;
            hour = Math.floor(minute / 60);
            minute = minute % 60;
            day = Math.floor(hour / 24);
            hour = hour % 24;
            return {
                day: day,
                hour: hour,
                minute: minute,
                seconds: seconds
            };
        }

        $scope.loadSpaces = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSpaces')
            }).then(function successCallback(data) {
                $scope.spaces = data.data;
                $scope.spaces.push($scope.allSpaces);

                $scope.showAlert = false;
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });

        };


        $scope.getSpaceData = function (currentSpace) {
                 if(currentSpace==="all"){

                 
				 $scope.showSpaceCharts = false;
                 $scope.showAllCustomerCharts = true;
				 $scope.openTab('trends');
				 $scope.loadData();
				 }else{
                 $scope.showSpaceCharts = true;
				 $scope.openTab('charts');
                 $scope.showAllCustomerCharts = false;
                 $scope.getSpaceMetrics(currentSpace);
				 }

        }


                $scope.getOpenVSClosedLineChartData = function () {
					
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getOpenVSClosedStatLog')+ "&period=" + $scope.openVSClosedLinePeriod +"&type=" + $scope.openVSClosedLineType + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate}, {v: obj.openedTicketNumber, f: ' '+obj.openedTicketNumber}, {v: obj.closedTicketNumber, f:' '+obj.closedTicketNumber }]});
                 }


                 $scope.lineClvsOpChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n["open"],
                             type: "number"
                         }, {
                             id: "close",
                             label: $scope.i18n["closed"],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


				$scope.getLogbyStatusChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getLogbyStatusChartData')+ "&period=" + $scope.logbyStatusChartPeriod   + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate},
					 {v: obj.openedTicketNumber, f:  " "+obj.openedTicketNumber},
					 {v: obj.waitingCustomerTicketNumber, f: " "+obj.waitingCustomerTicketNumber},
					 {v: obj.waitingProductTicketNumber, f: " "+obj.waitingProductTicketNumber},
					 {v: obj.inProgressTicketNumber, f: " "+obj.inProgressTicketNumber},
					 {v: obj.resolvedTicketNumber, f: " "+obj.resolvedTicketNumber}
					 ]});
                 }


                 $scope.lineLogbyStatusChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n["open"],
                             type: "number"
                         }, {
                             id: "waitingCustomer",
                             label: $scope.i18n["suspended_wfi"],
                             type: "number"
                         }, {
                             id: "waitingProduct",
                             label: $scope.i18n["resolved_maintenance"],
                             type: "number"
                         }, {
                             id: "inProgress",
                             label: $scope.i18n["inprogress"],
                             type: "number"
                         }, {
                             id: "resolved",
                             label: $scope.i18n["resolved_validated"],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


        $scope.getTimeMetricsByWeekChart = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getTimeMetricsByWeek') + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
            }).then(function successCallback(data) {
                $scope.statTimeMetrics = data.data;
                var TimeMetricsArray = [];
                for (var i = 0; i < $scope.statTimeMetrics.length; i++) {
                    var obj = $scope.statTimeMetrics[i];
                    TimeMetricsArray.push({c: [{v: obj.timeMetricsDate},
					 {v: obj.timeToFirstResponse, f:  " "+convertMS(obj.timeToFirstResponse).day + ":" +convertMS(obj.timeToFirstResponse).hour + ":" +convertMS(obj.timeToFirstResponse).minute},
					 {v: obj.timeToResolution, f:  " "+convertMS(obj.timeToResolution).day + ":" +convertMS(obj.timeToResolution).hour + ":" +convertMS(obj.timeToResolution).minute}

					 ]});
			   }


                $scope.timeMetricslineChartObject.data = {
                    "cols": [{
                            id: "day",
                            label: "Day",
                            type: "string"
                        }, {
                            id: "ttfr-id",
                            label: "timeToFirstResponse",
                            type: "number"
                        }, {
                            id: "ttr-id",
                            label: "timeToResolution",
                            type: "number"
                        }],
                    "rows": TimeMetricsArray
                };
                deferred.resolve(data);
                //                $scope.setResultMessage(data, "success");
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }
		
		
		
        $scope.getTimeMetricsByMonthChart = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getTimeMetricsByMonth') + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
            }).then(function successCallback(data) {
                $scope.statTimeMetrics = data.data;
                var TimeMetricsArray = [];
                for (var i = 0; i < $scope.statTimeMetrics.length; i++) {
                    var obj = $scope.statTimeMetrics[i];
                    TimeMetricsArray.push({c: [{v:obj.timeMetricsDate},
					 {v: obj.timeToFirstResponse, f:  " "+convertMS(obj.timeToFirstResponse).day + ":" +convertMS(obj.timeToFirstResponse).hour + ":" +convertMS(obj.timeToFirstResponse).minute},
					 {v: obj.timeToResolution, f:  " "+convertMS(obj.timeToResolution).day + ":" +convertMS(obj.timeToResolution).hour + ":" +convertMS(obj.timeToResolution).minute}

					 ]});
			   }


                $scope.timeMetricslineChartObject.data = {
                    "cols": [{
                            id: "day",
                            label: "Day",
                            type: "string"
                        }, {
                            id: "ttfr-id",
                            label: "timeToFirstResponse",
                            type: "number"
                        }, {
                            id: "ttr-id",
                            label: "timeToResolution",
                            type: "number"
                        }],
                    "rows": TimeMetricsArray
                };
                deferred.resolve(data);
                //                $scope.setResultMessage(data, "success");
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }
		
		
		
		
        $scope.getSatisfactionByWeekChart = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSatisfactionByWeek') + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
            }).then(function successCallback(data) {
                $scope.satsfactionStat = data.data;
                var satisfactionArray = [];
                for (var i = 0; i < $scope.satsfactionStat.length; i++) {
                    var obj = $scope.satsfactionStat[i];
                    satisfactionArray.push({c: [{v: obj.satisfactionDate},
					 {v: obj.customerSatisfactionPrc, f:  " "+obj.customerSatisfactionPrc+" %"},
					 {v: obj.customerTotalVotes, f:  " "+obj.customerTotalVotes+" votes"}

					 ]});
			   }


                $scope.cSatlineChartObject.data = {
                    "cols": [{
                            id: "date",
                            label: "Date",
                            type: "string"
                        }, {
                            id: "cSat-id",
                            label: "customerSatisfactionPrc",
                            type: "number"
                        }, {
                            id: "tot-id",
                            label: "totalVotes",
                            type: "number"
                        }],
                    "rows": satisfactionArray
                };
                deferred.resolve(data);
                //                $scope.setResultMessage(data, "success");
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }
				
		
        $scope.getSatisfactionByMonthChart = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSatisfactionByMonth') + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
            }).then(function successCallback(data) {
                $scope.satsfactionStat = data.data;
                var satisfactionArray = [];
                for (var i = 0; i < $scope.satsfactionStat.length; i++) {
                    var obj = $scope.satsfactionStat[i];
                    satisfactionArray.push({c: [{v: obj.satisfactionDate},
					 {v: obj.customerSatisfactionPrc, f:  " "+obj.customerSatisfactionPrc+" %"},
					 {v: obj.customerTotalVotes, f:  " "+obj.customerTotalVotes+" votes"}

					 ]});
			   }


                $scope.cSatlineChartObject.data = {
                    "cols": [{
                            id: "date",
                            label: "Date",
                            type: "string"
                        }, {
                            id: "cSat-id",
                            label: "customerSatisfactionPrc",
                            type: "number"
                        }, {
                            id: "tot-id",
                            label: "totalVotes",
                            type: "number"
                        }],
                    "rows": satisfactionArray
                };
                deferred.resolve(data);
                //                $scope.setResultMessage(data, "success");
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }
		
		


        $scope.loadBundle();
        $scope.loadData();
        $scope.loadAssignees();


        $('#ticketCharts').css('visibility', 'visible');
        $(".csLoadingBar").remove();

    };
        return ticketChartsCtrl;

});
