﻿/* alertsController.js - All alerts functionalities|| Author :G.B */
physicianPortalApp.controller('alertsController', ['$scope', '$window', 'baseRxcServices', 'config', '$http', '$location', '$rootScope', 'utils', 'prescriberService', '$sce', 'alertService', '$q', '$filter',
    function ($scope, $window, baseRxcServices, config, $http, $location, $rootScope, utils, prescriberService, $sce, alertService, $q, $filter) {
        $scope.init = function () {
            $scope.hasAlert = true;
            $scope.isLoading = true;
            $scope.allSelected = false;
            $scope.bigAllSelected = false;
            $scope.showAlertsNote = false;

            $scope.physicians = [];
            $scope.patientId = utils.parseQueryString('PatientId');
            $scope.caseId = utils.parseQueryString('CaseId');
            $scope.alerts = {};
            $scope.alerts.AlertAndNotificationsResult = [];

            $scope.placement = {
                options: [],
                selected: ''
            };

            $rootScope.activeUserMetaData = {
                clinicId: (utils.getCookie("ClinicId")) ? JSON.parse(utils.getCookie("ClinicId")) : 0,
                siteUserId: config.SiteUserId,
                portalId: config.PortalId,
                prescriberId: -1
            };

            $scope.SubscriptionTypeIds = {
                Patientcasestatuschange: config.Patientcasestatuschange,
                SOB: config.SOB,
                MissingInformation2ndattempt: config.MissingInformation2ndattempt,
                NewSecureMessage: config.NewSecureMessage,
                ESignPending: config.ESignPending
            }
            $scope.loadPage();

            $scope.$watch('bigCurrentPage', function (newValue, oldValue, scope) {
                if (newValue >= 1) {
                    var pagedData = $scope.alertsData.slice(
                        (newValue - 1) * $scope.itemsPerPage,
                        newValue * $scope.itemsPerPage
                    );
                    $scope.alerts.AlertAndNotificationsResult = pagedData;
                }

            }, true);

            $scope.$watch('alertsData', function (newValue, oldValue, scope) {
                if (newValue != undefined) {
                    var pagedData = $scope.alertsData.slice(
                        ($scope.bigCurrentPage - 1) * $scope.itemsPerPage,
                        $scope.bigCurrentPage * $scope.itemsPerPage
                    );
                    $scope.alerts.AlertAndNotificationsResult = pagedData;
                }

            }, true);

            $scope.$watch('alerts.AlertAndNotificationsResult', function (newValue, oldValue, scope) {
                if (newValue != undefined && newValue.length > 0) {
                    angular.forEach($scope.alerts.AlertAndNotificationsResult, function (itm) {
                        var toggleStatus = itm.isSelected;
                        console.log(toggleStatus);
                        var matchExist = $filter('filter')($scope.alertsData, { 'SiteUserAlertId': itm.SiteUserAlertId, 'isSelected': !toggleStatus });
                        if (matchExist.length > 0 && matchExist[0] != null) {
                            let index = $scope.alertsData.findIndex(function (record) { return (record.SiteUserAlertId === matchExist[0].SiteUserAlertId) });
                            if (index >= 0) {
                                $scope.alertsData[index] = itm;
                            }

                        }
                        itm.isSelected = toggleStatus;
                    });
                }
            }, true);

            $scope.$on("$destroy", function () {
                console.log('exiting alerts');
                $scope.placement.selected = "0_-1";
                $scope.loadAlerts()
            });

            $scope.toggleAll = function () {
                var toggleStatus = $scope.isAllSelected;
                angular.forEach($scope.alerts.AlertAndNotificationsResult, function (itm) { itm.isSelected = toggleStatus; });

            }

            $scope.optionToggled = function () {
                $scope.isAllSelected = $scope.alerts.AlertAndNotificationsResult.every(function (itm) { return itm.isSelected; })
            }
        }

        $scope.loadPage = function () {
            $scope.promiseSubscribers = prescriberService.getPrescribers();
            $scope.promiseSubscribers.then(function (precribers) {
                let allItem = { PhysicianId: 0 + '_' + -1, PhysicianName: 'All' };
                $scope.physicians = precribers;
                let fetchedPrescriberList = JSON.parse(JSON.stringify(precribers));
                if ($rootScope.activeUserMetaData.isAdmin) {
                    fetchedPrescriberList.splice(0, 0, allItem);
                }
                $scope.placement.options = fetchedPrescriberList;
                $scope.placement.selected = $scope.placement.options[0].PhysicianId;

                $scope.loadAlerts();

            }, function (error /*Error event should handle here*/) {
                console.log('error');
                $scope.isLoading = false;
            }, function (data /*Notify event should handle here*/) {
                console.log(data);
                $scope.isLoading = false;
            });
        }

        $scope.loadAlerts = function () {
            $scope.isLoading = true;
            var selectedPresId = $scope.placement.selected.split('_')[1];
            $rootScope.activeUserMetaData.dropdownPhysicianId = selectedPresId;

            if (selectedPresId == 0) {
                $scope.alertsData = [];
                $scope.hasAlert = false;
                $rootScope.AlertCount = 0;
                $scope.bigCurrentPage = 1;
                $scope.bigTotalItems = 0;
                $scope.isLoading = false;
                return;
            }

            $scope.promiseAlertsRefresh = alertService.refreshAlerts(selectedPresId, $scope.patientId, $scope.caseId);
            $scope.promiseAlertsRefresh.then(function (alerts) {

                angular.forEach(alerts, function (item, key) {
                    item.isSelected = false;
                    item.isDeleted = false;
                });

                $scope.alertsData = alerts;
                if (alerts != null && alerts !== undefined) {
                    $rootScope.AlertCount = $filter('filter')(alerts, { 'IsRead': false }).length;
                    $scope.hasAlert = $scope.alertsData.length > 0;
                }

                $scope.maxSize = 5;
                $scope.itemsPerPage = 10;
                $scope.bigCurrentPage = 1;
                $scope.bigTotalItems = alerts.length;
                if ($scope.caseId) { $scope.showAlertsNote = true; }
                $scope.isLoading = false;

            }, function (error /*Error event should handle here*/) {
                $scope.isLoading = false;
            }, function (data /*Notify event should handle here*/) {

                $scope.isLoading = false;
            });
        }
        $scope.updateAlerts = function (type, value) {

            if ($scope.allSelected && $scope.bigAllSelected) {
                angular.forEach($scope.alertsData, function (item, key) {
                    item.isSelected = true;
                });
            }

            let selectedAlertsData = $filter('filter')($scope.alertsData, { 'isSelected': true });

            if (selectedAlertsData.length == 0) {
                alert("Please select an alert!");
                return;
            }



            angular.forEach($scope.selectedAlerts, function (item, key) {
                if (type == 'IsRead') {
                    item.IsRead = value == 0 ? false : true;
                }
                else if (type == 'IsDeleted') {
                    item.isDeleted = value == 0 ? false : true;
                }
            });

            $scope.promiseAlertsUpdate = alertService.updateAlerts(selectedAlertsData, type, value);

            $scope.promiseAlertsUpdate.then(function (result) {
                $scope.alertsData = $filter('filter')($scope.alertsData, { 'isDeleted': false });
                $scope.isAllSelected = false;
                angular.forEach($scope.alertsData, function (item, key) {
                    item.isSelected = false;
                });

                $scope.loadAlerts();

            }, function (error /*Error event should handle here*/) {
                console.log('error');
            }, function (data /*Notify event should handle here*/) {
                console.log(data);
            });
        }


        $scope.markAsRead = function (siteUserAlertId, type, value) {
            let selectedAlertsData = $filter('filter')($scope.alertsData, { 'SiteUserAlertId': siteUserAlertId });

            if (selectedAlertsData.length > 0) {
                $scope.promiseAlertsUpdate = alertService.updateAlerts(selectedAlertsData, type, value);

                $scope.promiseAlertsUpdate.then(function (result) {
                    selectedAlertsData[0].IsRead = true;
                    $rootScope.AlertCount = $filter('filter')($scope.alertsData, { 'IsRead': false }).length;
                }, function (error /*Error event should handle here*/) {
                    console.log('error');
                }, function (data /*Notify event should handle here*/) {
                    console.log(data);
                });
            }
        }

        $scope.gotoProfile = function (patientId, caseId) {
            $location.path('/PatientProfile').search('PatientId', patientId).search('CaseId', caseId);
            $rootScope.milestoneNav = "patientProfile";

        }

        $scope.gotoSecureMsg = function (patientId, caseId) {
            $location.path('/SecureMsg');

        }

        $scope.gotoDashboard = function (patientId, caseId) {
            $location.path('/DashBoard');

        }
    }
]);