'use strict';

angular.module('trackingPage', ['chart.js', 'daterangepicker'])
    .controller('TrackingPageCtrl', [
        '$scope', '$state', 'ngToast', '$timeout', 'AppConfig', 'session', 'Util', '$http', '$stateParams', 'moment',
        '$uibModal', 'configServer',
        function ($scope, $state, ngToast, $timeout, AppConfig, session, Util, $http, $stateParams, moment,
                  $uibModal, configServer) {
            $scope.loadPath = '<span>' + Util.translate("COMMON.LOADING") + '</span>';
            $scope.fileId = $stateParams.file_id;
            $scope.folderId = $stateParams.folder_id;
            $scope.projectId = $stateParams.project_id;
            $scope.fileType = $stateParams.file_type;

            $scope.formatDate = AppConfig.FORMAT_DATE_SINGAPORE;
            $scope.listTrackingOpens = [];
            $scope.isSort = false;
            $scope.isSortOpen = false;
            $scope.paging = {
                currentPage: 1,
                currentPageOpen: 1,
                pageSizeView: "5",
                pageSizeOpen: "5"
            };
            $scope.maxSize = 5;
            $scope.predicate = "date_time";
            $scope.predicateOpen = "open_time";

            $scope.labels = [];
            $scope.data = [];
            $scope.ColorBar = ['#90EE90'];
            $scope.DataSetOverride = [{yAxisID: 'y-axis-1'}]; //y-axis-1 is the ID defined in scales under options.

            $scope.options = {
                legend: {display: false},
                responsive: true,  // set to false to remove responsiveness. Default responsive value is true.
                scales: {
                    yAxes: [
                        {
                            id: 'y-axis-1',
                            type: 'linear',
                            display: true,
                            position: 'left',
                            ticks: {
                                suggestedMin: 0,
                                suggestedMax: 5,
                                stepSize: 1
                            }
                        }]
                }
            };

            $scope.formatCompareDate = function (date) {
                return moment(date).format(AppConfig.MAX_EXPIRY_DATE_FORMAT);
            };
            if (session.getUser()) {
                $scope.currentUser = session.getUser();
            } else {
                session.getAuthUser(function (data) {
                    $scope.currentUser = data;
                }, function () {
                    // error cannot get auth user
                    Util.createToast({
                        className: 'danger',
                        content: 'COMMON.ERROR_MESSAGE'
                    });
                });
            }
            $scope.formatDateTime = function (date) {
                return Util.formatDateBasedOnDiff(date, "", $scope.currentUser.lang, $scope.currentUser.time_zone);
            };
            $scope.popupDocStartDate = {
                opened: false
            };

            $scope.popupDocEndDate = {
                opened: false
            };

            $scope.openDocStartDate = function () {
                $scope.popupDocStartDate.opened = true;
            };

            $scope.openDocEndDate = function () {
                $scope.popupDocEndDate.opened = true;
            };

            function loadFileInfo() {
                var paramFileInfo = {
                    project_id: $scope.projectId,
                    folder_id: ($scope.folderId) ? $scope.folderId : "0"
                };

                Util.createRequest(configServer.API_URL + "/files/" + $scope.fileId, "GET", paramFileInfo, function (response) {
                    if (response.status === 200) {
                        $scope.fileInfo = response.data.file;
                        $scope.startDate = moment(new Date(Util.formatDate($scope.fileInfo.create_date, 0, AppConfig.MAX_EXPIRY_DATE_FORMAT)));
                        loadDateRange($scope.startDate);
                        loadTrackingView();
                        loadTrackingOpen();
                        loadTrackingReportExternal();
                        $scope.drawFilePath();


                    } else {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + response.status
                        });
                        if(response.status === 403){
                            $state.go("dashboard");
                        }
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            }

            loadFileInfo();
            $scope.optsDate = {
                date: {
                    startDate: moment(),
                    endDate: moment()
                },
                options: {
                    opens: "center",
                    "alwaysShowCalendars": true,
                    locale: {
                        applyClass: 'btn-green',
                        applyLabel: "Apply",
                        fromLabel: "From",
                        format: "MM/DD/YYYY",
                        toLabel: "To",
                        cancelLabel: 'Cancel',
                        customRangeLabel: 'Custom range'
                    }
                }
            };

            function loadDateRange(start) {
                $scope.optsDate = {
                    date: {
                        startDate: start,
                        endDate: moment()
                    },
                    options: {
                        opens: "center",
                        "alwaysShowCalendars": true,
                        "autoUpdateInput": false,
                        locale: {
                            applyClass: 'btn-green',
                            applyLabel: "Apply",
                            fromLabel: "From",
                            format: "MM/DD/YYYY",
                            toLabel: "To",
                            cancelLabel: 'Cancel',
                            customRangeLabel: 'Custom range'
                        },
                        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')]
                        }
                    }
                };
            };

            var paramOpen = {
                sort_field: "",
                asc_sort: false,
                page_number: 1,
                page_size: 10,
                project_id: $scope.projectId,
                folder_id: $scope.folderId,
                type: $scope.fileType,
                s_date: $scope.optsDate.date.startDate.format('YYYY/MM/DD 00:00:00'),
                e_date: $scope.optsDate.date.endDate.format('YYYY/MM/DD 23:59:59')
            };

            $scope.doSort = function (sortCase) {
                $scope.paging.currentPage = 1; // reset to page 1 when sorting
                loadTrackingView(sortCase);
            };

            $scope.doSortOpen = function (sortCase) {
                $scope.paging.currentPageOpen = 1; // reset to page 1 when sorting
                loadTrackingOpen(sortCase);
            };

            $scope.pageChanged = function () {
                // Use $timeout to defer until ng-model (currentPage) is updated by uib-pagination
                $timeout(function () {
                    loadTrackingView();
                });
            };

            $scope.pageChangedOpen = function () {
                // Use $timeout to defer until ng-model (currentPageOpen) is updated by uib-pagination
                $timeout(function () {
                    loadTrackingOpen();
                });
            };


            var param = {
                sort_field: "open_time",
                asc_sort: false,
                page_number: 1,
                page_size: 10,
                project_id: $scope.projectId,
                folder_id: $scope.folderId,
                type: $scope.fileType,
                s_date: $scope.optsDate.date.startDate.format('YYYY/MM/DD 00:00:00'),
                e_date: $scope.optsDate.date.endDate.format('YYYY/MM/DD 23:59:59')
            };

            $scope.dataTrackingReportExternal = [];

            function loadTrackingReportExternal() {
                var paramFileReport = {
                    project_id: $scope.projectId,
                    s_date: $scope.optsDate.date.startDate.format('YYYY/MM/DD 00:00:00'),
                    e_date: $scope.optsDate.date.endDate.format('YYYY/MM/DD 23:59:59'),
                    type: $scope.fileType,
                    folder_id: ($scope.folderId) ? $scope.folderId : "0",
                    page_number: $scope.paging.currentPage,
                    page_size: $scope.paging.pageSizeView
                };
                Util.createRequest(configServer.API_URL + "/files/" + $scope.fileId + "/report/external", "GET", paramFileReport, function (response) {

                    if (response.status === 200) {
                        $scope.dataTrackingReportExternal = response.data.file_user_statistic;
                        var showData = [];
                        $scope.data = [];
                        $scope.labels = [];
                        angular.forEach($scope.dataTrackingReportExternal, function (item) {
                            $scope.labels.push(item.email);
                            showData.push(item.total_opened);
                            $scope.userTotalDownloaded += item.total_downloaded;
                        });
                        $scope.data.push(showData);
                    }

                });
            }

            function loadTrackingOpen(sortCase) {

                if (sortCase) {
                    if ($scope.predicateOpen === sortCase) {
                        $scope.isSortOpen = !$scope.isSortOpen;
                    } else {
                        $scope.isSortOpen = true;
                    }
                    paramOpen.asc_sort = $scope.isSortOpen;
                    paramOpen.sort_field = sortCase;
                    $scope.predicateOpen = sortCase;
                }

                paramOpen.s_date = $scope.optsDate.date.startDate.format('YYYY/MM/DD 00:00:00');
                paramOpen.e_date = $scope.optsDate.date.endDate.format('YYYY/MM/DD 23:59:59');
                paramOpen.page_number = $scope.paging.currentPageOpen;
                paramOpen.page_size = $scope.paging.pageSizeOpen;
                // reset state
                $scope.listTrackingOpens = [];
                if (paramOpen.type === "0")
                    return;
                Util.createRequest(configServer.API_URL + "/files/" + $scope.fileId + "/report/external/open", "GET", paramOpen, function (response) {
                    var status = response.status;
                    if (status === 200) {
                        $scope.listTrackingOpens = response.data.view_file.content;
                        $scope.totalItemsOpen = response.data.view_file.total_elements;
                        $scope.totalPageOpen = Math.ceil($scope.totalItemsOpen / $scope.paging.pageSizeOpen);
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            }

            function loadTrackingView(sortCase) {

                if (sortCase) {
                    if ($scope.predicate === sortCase) {
                        $scope.isSort = !$scope.isSort;
                    } else {
                        $scope.isSort = true;
                    }
                    param.asc_sort = $scope.isSort;
                    param.sort_field = sortCase;
                    $scope.predicate = sortCase;
                }
                param.s_date = $scope.optsDate.date.startDate.format('YYYY/MM/DD 00:00:00');
                param.e_date = $scope.optsDate.date.endDate.format('YYYY/MM/DD 23:59:59');
                param.page_number = $scope.paging.currentPage;
                param.page_size = $scope.paging.pageSizeView;
                // reset state
                if ($scope.fileType === 1) {
                    Util.createRequest(configServer.API_URL + "/files/" + $scope.fileId + "/report/external/open", "GET", param, function (response) {
                        var status = response.status;
                        if (status === 200) {
                            $scope.listTrackingViews = response.data.data.content;
                            $scope.totalItems = response.data.data.total_elements;
                            $scope.totalPage = Math.ceil($scope.totalItems / $scope.paging.pageSizeView);
                        }
                    }, function (error) {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + error.status
                        });
                    });
                } else {
                    Util.createRequest(configServer.API_URL + "/files/" + $scope.fileId + "/report/internal/open", "GET", param, function (response) {
                        var status = response.status;
                        if (status === 200) {
                            $scope.listTrackingViews = response.data.data.content;
                            $scope.totalItems = response.data.data.total_elements;
                            $scope.totalPage = Math.ceil($scope.totalItems / $scope.paging.pageSizeView);
                        } else {
                            Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + status});
                        }
                    }, function (error) {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + error.status
                        });
                    });
                }
            }

            $scope.createReport = function (valid) {

                if (!valid) {
                    return;
                }
                $scope.paging.currentPage = 1; // reset to page 1 on new report
                $scope.paging.currentPageOpen = 1; // reset to page 1 on new report
                loadTrackingReportExternal();
                loadTrackingView();
                loadTrackingOpen();
            };


            $scope.showConfirmRevokeMember = function (addressbookId, fileId, folderId, projectId) {
                //show confirm revoke
                return $uibModal.open({
                    templateUrl: 'components/modal-template/confirm_delete_modal.html',
                    size: 'md',
                    controller: ['$scope', '$rootScope', '$uibModalInstance', '$translate', function ($scope, $rootScope, $uibModalInstance, $translate) {
                        $translate(['COMMON.BUTTON_CANCEL', 'COMMON.BUTTON_OK', 'REPORT_TRACKING.CONFIRM_REVOKE_MSG', 'REPORT_TRACKING.CONFIRM_REVOKE_TITLE']).then(function (translations) {

                            $scope.opts = {
                                title: translations['REPORT_TRACKING.CONFIRM_REVOKE_TITLE'],
                                message: translations['REPORT_TRACKING.CONFIRM_REVOKE_MSG'],
                                lblAccept: translations['COMMON.BUTTON_OK'],
                                lblDismiss: translations['COMMON.BUTTON_CANCEL'],
                            };
                            $scope.onClose = function () {
                                $uibModalInstance.close();
                            };

                            $scope.onAccept = function () {
                                doRevokeUser(addressbookId);
                                $uibModalInstance.close();
                            };

                            function doRevokeUser(id) {
                                var param = {
                                    "address_book_id": id,
                                    "project_id":projectId,
                                    "folder_id": folderId
                                };

                                Util.createRequest(configServer.API_URL + "/files/" + fileId + "/drm/license", "DELETE", param, function (response) {
                                    if (response.status === 200) {
                                        Util.createToast({
                                            className: 'success',
                                            content: 'COMMON.MESSAGE.REVOKE_SUCCESS'
                                        });
                                        $rootScope.$broadcast("load_tracking");
                                    } else {
                                        //toast fail
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'COMMON.ERROR_MESSAGE'
                                        });
                                    }

                                }, function (error) {
                                    //toast fail
                                    Util.createToast({
                                        className: 'danger',
                                        content: 'SERVER_ERROR.' + error.status
                                    });
                                });
                            }
                        });

                    }]
                }).result.catch(function (resp) {
                    if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) throw resp;
                });

            };

            //do revoke
            $scope.$on("load_tracking", loadTracking);
            function loadTracking(event, value) {
                $state.go($state.current, {}, {reload: true});
            };

            $scope.listFolder = [];

            function getFilePath() {
                $scope.isLoading = true;
                Util.createRequest(configServer.API_URL + "/folders/" + $scope.folderId + "/path", "GET", {project_id: $scope.projectId}, function (response) {
                    if (response.status === 200) {
                        var folders = response.data;

                        $scope.separator = '&nbsp;<span class="separator-icon small d-inline-block"><i class="fa fa-chevron-right" aria-hidden="true"></i></span>&nbsp;';
                        $scope.sentFiles = '<a href="#!/my-email/0" >' + Util.translate("COMMON.MY_EMAIL") + '</a>';
                        $scope.currentFol = "";
                        // apply folder tree link
                        if (folders && folders.length > 0) {
                            for (var i = 0; i < folders.length; i++) {
                                $scope.listFolder.push(folders[i]);
                            }
                        }
                        $scope.folderBefor = $scope.separator + '<a href="#!/my-email/' + $scope.currentFolder.folder.folder_id + '">' + $scope.currentFolder.folder.name + '</a>';
                        $scope.fileName = $scope.separator + "<span>" + $scope.fileInfo.title + "</span>";
                        $scope.isLoading = false;
                    } else {
                        $scope.isLoading = false;
                        Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + response.status});
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            }

            function getCurrentFolder() {

                Util.createRequest(configServer.API_URL + "/folders/" + $scope.folderId, "GET", {project_id: $scope.projectId}, function (response) {
                    if (response.status === 200) {
                        $scope.currentFolder = response.data;
                        getFilePath();
                    } else {
                        Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + response.status});
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            }

            $scope.drawFilePath = function () {

                //call project get project name
                Util.createRequest(configServer.API_URL + "/projects/" + $scope.projectId, "GET", {}, function (response) {
                    if (response.status === 200) {
                        $scope.projectName = response.data.name;
                        getCurrentFolder();
                    } else {
                        Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + response.status});
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });

            };
        }
    ]);
