'use strict';
define(function(require) {
    let module = require('components/identimetricsFOTM/module');
    module.controller('fotm', ['$scope', '$rootScope', '$http', '$httpParamSerializer', '$q', '$timeout', '$sce', '$injector', 'forms', 'idMService', 'attService', 'kioskService', function($scope, $rootScope, $http, $httpParamSerializer, $q, $timeout, $sce, $injector, forms, idMService, attService, kioskService) {
        idMService.init()
        $scope.idMService = idMService
        $scope.attService = attService
        $scope.kioskService = kioskService
        $scope.forms = forms
        $scope.ctrlData = {
            args: idmFOTMArgs,
            userArgs: idmFOTMArgs.userArgs,
            ticker: new Date(),
            midnight: new Date(),
            textFilter: '',
            toggleSel: true,
            localValidations: ["noStudent", "wrongSchool"],
            reportControls: {
                dateStart: (new Date()).toLocaleDateString(),
                dateEnd: (new Date()).toLocaleDateString()
            },
            entry: {},
            scanEntries: [],
            scanEntriesUnfiltered: [],
            selectedEntries: [],
            kioskEntries: []
        }
        $scope.ctrlData.midnight.setHours(0,0,0,0)
        $scope.ctrlData.attType = $scope.ctrlData.args.attendanceMode.charAt(0).toUpperCase() + $scope.ctrlData.args.attendanceMode.slice(1)
        $scope.ctrlData.params = {
            "att_mode_code": `ATT_Mode${$scope.ctrlData.attType}`,
            "dateStart": $scope.ctrlData.args.dateStart,
            "dateEnd": $scope.ctrlData.args.dateEnd,
            "scanType": $scope.ctrlData.args.scanType,
            "termLength": $scope.ctrlData.args.termLength
        }
        $scope.ctrlData.map = idMService.map
        $scope.ctrlData.gwCtrlData = idMService.gwCtrlData
        idMService.ctrlData = $scope.ctrlData
        attService.ctrlData = $scope.ctrlData
        kioskService.ctrlData = $scope.ctrlData
        $scope._ = _
        //$scope.prevErrorFilter = {}

        pss_get_texts("psx.htmlc.idmFOTM")

        $scope.placeholderText = pss_text('psx.htmlc.idmFOTM.placehold_wait')
        $scope.dOpts = {
            "dateStyle": "medium"
        }
        $scope.tOpts = {
            "timeStyle": "medium"
        }
        $scope.ctrlData.map.scanResultsResolved = _.clone($scope.ctrlData.map.scanResults)

        $scope.independentFixes = {
            "saveDaily": ["specificSections", "specificPeriods", "allSections", "allPeriods"],
            "allPeriods": ["saveDaily", "specificPeriods"],
            "specificPeriods": ["saveDaily", "allPeriods"],
            "allSections": ["saveDaily", "specificSections"],
            "specificSections": ["saveDaily", "allSections"]
        }

        $scope.$watch("ctrlData.ticker", function() {
            attService.checkFocus()
            if ($scope.ctrlData.ticker.getSeconds() == 0) {
                $scope.ctrlData.dayStarted = kioskService.kioskCheckSchedule()
            }
        })

        $scope.$watch("ctrlData.textFilter", function() {
            if ($scope.ctrlData.textFilter != '') {
                $scope.ctrlData.scanEntries = (
                    _.chain($scope.ctrlData.scanEntriesUnfiltered)
                    .filter( e=> JSON.stringify(e).toLowerCase().includes( $scope.ctrlData.textFilter.toLowerCase() ) )
                    .value()
                )
            } else {
                $scope.ctrlData.scanEntries = $scope.ctrlData.scanEntriesUnfiltered
            }
        })

        $scope.$watch("ctrlData.toggleSel", function() {
            if ($scope.ctrlData.scanEntries) {
                $scope.ctrlData.scanEntries.map( e=>{
                    e.selected = $scope.ctrlData.toggleSel
                } )
            }
        })

        $scope.$watch("ctrlData.errorFix", function() {
            if ($scope.ctrlData.errorFix && $scope.ctrlData.errorFix.includes("editTime")) {
                angular.element(".ui-datepicker-trigger[disabled='disabled']").removeAttr("disabled")
            }
        })

        if (window.location.href.includes("kioskReport.html")) {
            $scope.$watch("ctrlData.reportControls", function() {
                kioskService.loadKiosk()
            }, true)
        }

        if (window.location.href.includes("kioskDashboard.html")) {
            $scope.$watch("ctrlData.reportControls.dateStart", function() {
                kioskService.testValidateAll()
            })
        }

        $scope.logScope = function() {
            console.log($scope)
        }
        $scope.logScope()

        let PaginationHelper = require('components/widgets/models/PaginationHelperWithFilterTracking');
        $scope.pgController = new PaginationHelper();

        $scope.selected = function() {
            return (
                _.chain( $scope.pgController.filteredItemsAllPages )
                .filter( e=> JSON.stringify(e).toLowerCase().includes( $scope.ctrlData.textFilter.toLowerCase() ) )
                .filter( e=> e.selected )
                .value()
            )
        }

        $scope.selectedStudents = function() {
            let ids = (
                _.chain( $scope.selected() )
                .filter( e=> e.selected )
                .pluck( 'studentid' )
                .uniq()
                .value()
            )

            return ids;
        }
        
        $scope.buildSel = function() {
            idMService.buildSel($scope.selected(), "studentid")
        }

        $scope.export = function() {
            loadingDialog( `Exporting entries` );

            let fields = ["lastfirst", "student_number", "grade_level", "scanDate", "term", "att_comment", "attCode", "description", "course_name", "expression", "codeType", "typeCount", "overallCount"]
            let fieldTitles = ["student", "student number", "grade", "scan date", "term", "attendance comment", "code", "description", "course", "expression", "code type", "type count", "overall count"]
            let name = `Attendance Entries ${$scope.ctrlData.args.isoFormat($scope.ctrlData.ticker)}`

            idMService.exportCSV($scope.selected(), fields, fieldTitles, name)

            closeLoading();
        }

        $scope.exportKiosk = function(dataSet, type) {
            let fields = ["scanTime", "scanDate", "lastfirst", "scanIdentifier", "scanTerminal", "scanResult"]
            let fieldTitles = ["Scan Time", "Scan Date", "Student", "Scanned ID", "Kiosk", "Result"]
            let name = `Kiosk ${type} ${$scope.ctrlData.args.isoFormat($scope.ctrlData.ticker)}`

            idMService.exportCSV(dataSet, fields, fieldTitles, name)
        }

        $scope.identifierPlaceholder = function() {
            if (document.getElementById("studentIdentifier") == document.activeElement) {
                $scope.placeholderText = pss_text('psx.htmlc.idmFOTM.placehold_ready')
            } else {
                $scope.placeholderText = pss_text('psx.htmlc.idmFOTM.placehold_wait')
            }
        }

        $scope.studentSearch = function() {
            if ('' !== $scope.ctrlData.entry.studentIdentifier) {
                let studentList = []
                if (!$scope.ctrlData.entry.studentIdentifier.match(/^\d+$/)) {
                    studentList = _.filter($scope.ctrlData.args.currentSchoolStudents, function(student) {
                        return student.lastfirst.toLowerCase().startsWith($scope.ctrlData.entry.studentIdentifier.toLowerCase())
                    })
                    $scope.students = studentList
                }
            } else {
                $scope.students = []
            }
        }

        $scope.toggleErrorFix = function(fix, pushOnly) {
            let toggleFix = true
            if ($scope.independentFixes[fix]) {
                if (_.intersection($scope.independentFixes[fix], $scope.ctrlData.errorFix).length > 0) {
                    toggleFix = false
                }
            } 
            if (toggleFix) {
                if ($scope.ctrlData.errorFix.includes(fix) && !pushOnly) {
                    $scope.ctrlData.errorFix = _.without($scope.ctrlData.errorFix, fix)
                } else if (!$scope.ctrlData.errorFix.includes(fix)) {
                    $scope.ctrlData.errorFix.push(fix)
                }
            }
        }

        $scope.evalSectionState = function(entry, errorCodes, enrollment) {
            if ($scope.ctrlData.errorCodes && $scope.ctrlData.errorCodes.length > 0) {
                if ($scope.ctrlData.errorFix.length == 0) {
                    if (errorCodes.includes("multiSection") && entry.multiSection[enrollment.period_number]) {
                        return "question"
                    }
                    if (errorCodes.includes("overlap") && _.pluck(entry.currentClasses, "period_number").includes(enrollment.period_number)) {
                        return "question"
                    }
                }
    
                if (errorCodes.includes("multiSection")) {
                    if ($scope.ctrlData.errorFix.includes("specificSections")) {
                        if (!entry.specificSections || entry.specificSections.length == 0) {
                            return "question"
                        }
                        if (entry.specificSections && entry.specificSections.includes(enrollment.ccid)) {
                            return "check"
                        }
                    }
                    if ($scope.ctrlData.errorFix.includes("allSections")) {
                        if ($scope.ctrlData.errorFix.includes("allPeriods")) {
                            return "check"
                        }
                        if (!entry.specificPeriods) {
                            return "check"
                        }
                        if (entry.specificPeriods.length == 0) {
                            return "check"
                        }
                        if (errorCodes.includes("overlap")) {
                            if (!$scope.ctrlData.errorFix.includes("specificPeriods")) {
                                return "check"
                            }
                            if ($scope.ctrlData.errorFix.includes("specificPeriods") && entry.specificPeriods.includes(enrollment.period_number)) {
                                return "check"
                            }
                        } else {
                            if (!entry.specificPeriods) {
                                return "check"
                            }
                            if (entry.specificPeriods && entry.specificPeriods.includes(enrollment.period_number)) {
                                return "check"
                            }
                        }
                    }
                }
    
                if (errorCodes.includes("overlap")) {
                    if ($scope.ctrlData.errorFix.includes("specificPeriods")) {
                        if ((!entry.specificPeriods || entry.specificPeriods.length == 0)) {
                            return "question"
                        }
                        if (entry.specificPeriods.includes(enrollment.period_number)) {
                            if (errorCodes.includes("multiSection")) {
                                if (!entry.multiSection[enrollment.period_number]) {
                                    return "check"
                                }
                            } else {
                                return "check"
                            }
                        }
                    }
                    if ($scope.ctrlData.errorFix.includes("allPeriods")) {
                        if (errorCodes.includes("multiSection")) {
                            if (!entry.multiSection[enrollment.period_number]) {
                                return "check"
                            } else {
                                return "question"
                            }
                        } else {
                            return "check"
                        }
                    }
                }
    
                return "times"
            }
        }
        
        $scope.submitAttendance = function(entry, kioskMode) {
            loadingDialog(pss_text('psx.htmlc.idmFOTM.loading'), "identimetricsFOTMEntry")

            entry = attService.prepAttendance(entry)

            if (kioskMode) {
                kioskService.submitAttendance(entry, kioskMode)
            } else {
                attService.submitAttendance(entry, kioskMode)
            }
        }
        
        attService.init()
        kioskService.init()
        
        // Check ez-update status
        $scope.auth = true;
        
        idmxTdyAuth().then(r => {
            $scope.auth = r;
        });
    }]);
});