'use strict';
define(function(require) {
	let module = require('components/identimetricsFOTM/module');
	module.factory('kioskService', ['$http', '$httpParamSerializer', '$filter', '$rootScope', '$timeout', 'forms', 'idMService', 'attService', function($http, $httpParamSerializer, $filter, $rootScope, $timeout, forms, idMService, attService) {
        pss_get_texts("psx.htmlc.idmFOTM")
        var kioskService = {
            init: function() {
                if (window.location.href.includes("scanKiosk.html")) {
                    if (kioskService.ctrlData.args.kioskModeEnable == "1") {
                        kioskService.ctrlData.dayStarted = kioskService.kioskCheckSchedule()
                        kioskService.ctrlData.args.kioskMode = 1

                        kioskService.ctrlData.args.attCodes.forEach(function(attCode) {
                            if (!kioskService.ctrlData.args.kioskArgs.kioskCodeOptions.includes(attCode.att_codeKey)) {
                                kioskService.ctrlData.args.attCodes = _.without(kioskService.ctrlData.args.attCodes, attCode)
                            }
                        })

                        if (kioskService.ctrlData.args.kioskSuppressTardySlip == "1") {
                            kioskService.ctrlData.args.shouldPrintTardySlip = "0"
                        }

                        setInterval(function() {
                            kioskService.keepAlive()
                        }, 60000)
                    } else {
                        window.location = "/admin/attendance/functions/idm_scanAttendance.html"
                    }
                }

                if (window.location.pathname.includes("kioskReport.html")) {
                    var linkScopes = setInterval(function() {
                        if (kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskErrors"] && kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskAllowed"]) {
                            
                            kioskService.ctrlData.countdown = 5
                            kioskService.ctrlData.kioskUpdateCount = 0
                            kioskService.loadKiosk()
                            setInterval(function() {
                                if (kioskService.ctrlData.args.liveScanning && !kioskService.ctrlData.loadingKiosk) {
                                    kioskService.ctrlData.countdown--
                                    if (kioskService.ctrlData.countdown == 0) {
                                        kioskService.loadKiosk()
                                    }
                                }
                            }, 1000)

                            clearInterval(linkScopes)
                        }
                    }, 750)
                }

                if (window.location.pathname.includes("kioskDashboard.html")) {
                    var gwScope = setInterval(function() {
                        if (kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskPredictions"]) {
                            kioskService.validateAll()

                            clearInterval(gwScope)
                        }
                    }, 750)
                    
                }
            },
            keepaliveCounter: 0,
            keepAlive: function() {
                return $http({
                    url: "/admin/attendance/functions/idm_helper.html?helperType=keepalive",
                    method: "GET",
                    params: {"counter": kioskService.keepaliveCounter}
                }).then(function() {
                    kioskService.keepaliveCounter++
                })
            },
            kioskCheckSchedule: function() {
                let dayStarted = false
                if (kioskService.ctrlData.args.currentDay.periodSchedule.length > 0) {
                    if (kioskService.ctrlData.args.daystartTime.getTime() <= kioskService.ctrlData.ticker.getTime() && kioskService.ctrlData.ticker.getTime() < kioskService.ctrlData.args.dayendTime.getTime()) {
                        dayStarted = kioskService.ctrlData.args.daystartTime
                    } else {
                        if (kioskService.ctrlData.args.kioskAttendanceBeforeSOD == "1") {
                            dayStarted = kioskService.ctrlData.args.daystartTime
                        }
                    }
                }
                return dayStarted
            },
            submitAttendance: function(entry) {
                let kioskAuth = forms.read("#idmFOTMKioskAuth input")
                let submitObj = {
                    att_date: entry.timeData.att_date
                }

                kioskAuth.scanDate.value = get_localized_date(new Date(`${entry.timeData.att_date}T00:00:00`))
                kioskAuth.scanTime.value = String((entry.timeData.submitHour24*60*60 + entry.timeData.submitMinute*60))
                kioskAuth.studentsdcid.value = entry.studentsdcid
                kioskAuth.studentIdentifier.value = entry.studentIdentifier
            
                Object.keys(entry).forEach(function(key) {
                    submitObj[key] = entry[key]
                })
                Object.keys(kioskAuth).forEach(function(key) {
                    submitObj[kioskAuth[key].name] = kioskAuth[key].value
                })

                kioskService.ctrlData.lastKiosk = {
                    studentsdcid: entry.studentsdcid,
                    studentid: entry.studentid,
                    studentIdentifier: entry.studentIdentifier,
                    class: "feedback-error",
                    lastfirst: "UNKNOWN STUDENT",
                    duration: parseInt(kioskService.ctrlData.args.kioskDurationError) * 1000
                }

                kioskService.kioskValidation(submitObj).then(function(response) {
                    for (const[key, value] of Object.entries(response)) {
                        kioskService.ctrlData.lastKiosk[key] = value
                    }
                    if (!kioskService.ctrlData.lastKiosk.lastfirst) {
                        kioskService.ctrlData.lastKiosk.lastfirst = "UNKNOWN STUDENT"
                    }

                    //let kioskResult = response.resultOverride != "" ? Number(response.resultOverride) : Number(kioskService.checkKioskValidation(submitObj.att_date, response))
                    
                    let kioskResult = Number(kioskService.checkKioskValidation(submitObj.att_date, response))
                    if (kioskService.ctrlData.args.kioskArgs.kioskDenialReasons.includes(response.resultOverride)) {
                        kioskResult = Number(response.resultOverride)
                    }
                    kioskService.ctrlData.lastKiosk.result = kioskResult

                    let resultData = {ac: "prim"}
                    resultData[`CF-[U_IDENTIMETRICS_ATT_FOTM_KIOSK:${response.kioskid}]result`] = kioskResult

                    $http({
                        url: `/admin/attendance/functions/idm_helper.html?helperType=changesRecorded`,
                        method: "POST",
                        data: $httpParamSerializer(resultData),
                        headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                    })

                    if (kioskResult > 0) {
                        kioskService.ctrlData.lastKiosk.duration = parseInt(kioskService.ctrlData.args.kioskDurationWelcome) * 1000
                    }

                    if (!kioskService.ctrlData.dayStarted || !entry.attendanceCode || entry.attendanceCode.suppressKioskPopup != "1" || kioskResult < 1) {
                        let psDialogHolder = null
                        psDialogHolder = $j("#idMKioskDialogScanned")
                        let audio = new Audio("/admin/attendance/functions/idm_alarm.wav")
                        if (kioskResult < 0) {
                            audio.play()
                        }
                           
                        psDialog({
                            id: "kioskDialog",
                            content: psDialogHolder,
                            type: "dialogM",
                            classes: {
                                "ui-dialog": "idm_kioskMessage",
                                "ui-dialog-content": "idm_kioskMessage",
                                "ui-dialog-titlebar": "idm_kioskMessageTitle"
                            },
                            close: function() {
                                $j('#idMFOTMKioskDialogHolder').append(psDialogHolder);
                                audio.pause()
                                delete kioskService.ctrlData.lastKiosk.studentid
                                delete kioskService.ctrlData.lastKiosk
                            }
                        })

                        $timeout(function() {
                            if (angular.element("#idMKioskDialogScanned").parent().css("display") != "none") {
                                angular.element("#idMKioskDialogScanned").parent().dialog("close")
                            }
                        }, kioskService.ctrlData.lastKiosk.duration)
                    } else {
                        delete kioskService.ctrlData.lastKiosk.studentid
                        delete kioskService.ctrlData.lastKiosk
                    }
                    
                    if (kioskResult >= 0 && kioskService.ctrlData.dayStarted && kioskService.ctrlData.userArgs.kiosk.noAttendanceRecord != "1") {
                        if (kioskService.ctrlData.args.kioskAttendanceBeforeSOD == "1" && entry.timeData.useTime.getTime() < kioskService.ctrlData.dayStarted.getTime()) {
                            entry.timeData = idMService.prepareTime(entry, kioskService.ctrlData.dayStarted)
                        }
                        attService.submitAttendance(entry)
                    } else {
                        attService.clearSettings()
                        closeLoading()
                    }
                })
            },
            kioskValidation: function(entry, noCreate, att_date) {
                let submitObj = {
                    att_date: att_date || entry.att_date
                }
                if (entry) {
                    submitObj = {
                        att_date: submitObj.att_date,
                        studentid: entry.studentid,
                        studentsdcid: entry.studentsdcid,
                        studentIdentifier: entry.studentIdentifier
                    }
                }

                if (noCreate) {
                    submitObj.validateOnly = 1
                } else {
                    submitObj.ac = "prim"

                    for (const [key, value] of Object.entries(entry)) {
                        if (key.includes("CF-")) {
                            submitObj[key] = value
                        }
                    }
                }

                return $http({
                    url: "/admin/attendance/functions/idm_helper.html?helperType=validateKiosk",
                    method: "POST",
                    data: $httpParamSerializer(submitObj),
                    headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                }).then(function(response) {
                    response.data.pop()
                    if (response.data.length == 1) {
                        return response.data[0]
                    } else {
                        return response.data
                    }
                })
            },
            testValidateAll: function() {
                if (kioskService.ctrlData.lastSearchDate != kioskService.ctrlData.reportControls.dateStart) {
                    kioskService.validateAll()
                }
            },
            validateAll: function() {
                kioskService.ctrlData.loadingKiosk = true
                //kioskService.ctrlData.kioskPredictions = []
                let searchDate = kioskService.ctrlData.args.isoFormat(new Date(kioskService.ctrlData.reportControls.dateStart))
                kioskService.kioskValidation(false, true, searchDate).then(function(response) {
                    response.forEach(function(stu) {
                        let cacheStu = _.findWhere(kioskService.ctrlData.args.students, {studentsdcid: stu.studentsdcid})
                        if (cacheStu) {
                            stu.scanDateJS = new Date(`${searchDate}T00:00:00`)
                            stu.kioskResult = kioskService.checkKioskValidation(searchDate, stu)
                            if (stu.dateStartOverride) {
                                stu.dateStartOverrideJS = new Date(`${stu.dateStartOverride}T00:00:00`)
                                stu.dateEndOverrideJS = new Date(`${stu.dateEndOverride}T00:00:00`)
                            }
                            stu.studentIdentifier = cacheStu.studentIdentifier
                        }
                    })
                    kioskService.ctrlData.kioskPredictions = response
                    kioskService.ctrlData.lastSearchDate = kioskService.ctrlData.reportControls.dateStart
                    kioskService.ctrlData.loadingKiosk = false
                })
            },
            checkKioskValidation: function(att_date, response) {
                let validResult = "1"
                if (!response.studentsdcid) {
                    validResult = "-1"
                }
                if (validResult == "1") {
                    kioskService.ctrlData.args.kioskArgs.kioskDenialReasons.forEach(function(denialReason) {
                        if (validResult == "1") {
                            switch (denialReason) {
                                /*
                                case "-1":
                                    if (!response.studentsdcid) {
                                        validResult = denialReason
                                    }
                                    break
                                */
                                case "-2":
                                    if (response.schoolid != kioskService.ctrlData.args.curschoolid) {
                                        validResult = denialReason
                                    }
                                    break
                                case "-3":
                                    if (_.intersection(idmFOTMArgs.denyCodes,response.att_codes).length > 0){
                                        validResult = denialReason
                                    }
                                    break
                                case "-4":
                                    let entryDate = new Date(response.entrydate)
                                    let exitDate = new Date(response.exitdate)
                                    if (response.enroll_status != "0" || new Date(att_date) < entryDate || new Date(att_date) > exitDate){
                                        validResult = denialReason
                                    }
                                    break
                                case "-5":
                                    if (Number(response.membershipvalue) == 0) {
                                        validResult = denialReason
                                    }
                                    break
                                case "-6":
                                    if (response.lastScan) {
                                        let lastScan = new Date(`${att_date}T${response.lastScan}`)
                                        let minDiff = Math.abs(kioskService.ctrlData.ticker - lastScan) / (60 * 1000)
                                        if (minDiff < kioskService.ctrlData.args.kioskDenyRecentMinutes) {
                                            validResult = denialReason
                                        }
                                    }
                                    break
                                case "none":
                                    break
                            }
                        }
                    })
                }

                return validResult
            },
            linkFilters: function() {
                $timeout(function() {
                    if (kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskErrors"].gridWidgetCtrlData.filterTracker.filters.length > 1) {
                        let changedFilter = true
                        if (
                            kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskAllowed"].gridWidgetCtrlData.filterString == kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskErrors"].gridWidgetCtrlData.filterString &&
                            _.isEqual(kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskAllowed"].gridWidgetCtrlData.filterTracker.filters,kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskErrors"].gridWidgetCtrlData.filterTracker.filters)
                        ) {
                            changedFilter = false
                        }
                        kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskAllowed"].gridWidgetCtrlData.filterString = kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskErrors"].gridWidgetCtrlData.filterString
                        kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskAllowed"].gridWidgetCtrlData.filterTracker.filters = kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskErrors"].gridWidgetCtrlData.filterTracker.filters
                        kioskService.ctrlData.gwCtrlData["gridScope_ctrlData.kioskAllowed"].refreshAll()
            
                        

                        if (
                            kioskService.ctrlData.midnight.getTime() <= (new Date(kioskService.ctrlData.reportControls.dateEnd)).getTime() && 
                            kioskService.ctrlData.midnight.getTime() >= (new Date(kioskService.ctrlData.reportControls.dateStart)).getTime()
                        ) {
                            kioskService.ctrlData.args.liveScanning = true
                            kioskService.ctrlData.args.allowLiveScanning = true
                        } else {
                            kioskService.ctrlData.args.liveScanning = false
                            kioskService.ctrlData.args.allowLiveScanning = false
                        }
            
                        if (changedFilter) {
                            kioskService.loadKiosk()
                        }
                    }
                }, 50)
            },
            updateKioskResult: function(entry) {
                if (entry.resolvedResultCode != "") {
                    entry.resolvedResult = kioskService.ctrlData.map.scanResultsInverted[entry.resolvedResultCode]
                }
            },
            resolveKiosk: function(entry, fullDetails, forceValue) {
                kioskService.ctrlData.loadingKiosk = true
                let timeData = idMService.prepareTime(entry, kioskService.ctrlData.ticker)

                entry.loading = true
                entry.resolved = forceValue ?? "1"
                entry.resolvedBy = kioskService.ctrlData.args.user
                entry.resolvedTime = `${timeData.submitHour12Pad}:${timeData.submitMinutePad} ${timeData.submitMeridian}`
                
                if (fullDetails) {
                    entry.editDetails = true
                    if (entry.resolvedResultCode == "") {
                        entry.resolvedResultCode = entry.scanCode
                    }
                } else {
                    kioskService.updateKioskResolved(entry)
                }
            },
            updateKioskResolved: function(entry) {
                let timeData = idMService.prepareTime(entry, kioskService.ctrlData.ticker)
                let submitData = {
                    "ac": "prim",
                    "U_IDENTIMETRICS_ATT_FOTM_KIOSK.id": entry.kioskid
                }
                submitData[`CF-[U_IDENTIMETRICS_ATT_FOTM_KIOSK:${entry.kioskid}]resolved`] = entry.resolved
                submitData[`CF-[U_IDENTIMETRICS_ATT_FOTM_KIOSK:${entry.kioskid}]resolvedBy`] = kioskService.ctrlData.args.usersdcid
                submitData[`CF-[U_IDENTIMETRICS_ATT_FOTM_KIOSK:${entry.kioskid}]resolvedTime`] = String((timeData.useTime.getHours()*60*60 + timeData.useTime.getMinutes()*60))
                if (entry.editDetails) {
                    submitData[`CF-[U_IDENTIMETRICS_ATT_FOTM_KIOSK:${entry.kioskid}]resolvedResult`] = entry.resolvedResultCode
                    submitData[`CF-[U_IDENTIMETRICS_ATT_FOTM_KIOSK:${entry.kioskid}]resolvedNote`] = entry.resolvedNote
                }

                $http({
                    url: `/admin/attendance/functions/idm_helper.html?helperType=changesRecorded`,
                    method: "POST",
                    data: $httpParamSerializer(submitData),
                    headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                }).then(function(response) {
                    kioskService.loadKiosk(entry)
                })
            },
            resetResolve: function(entry) {
                kioskService.ctrlData.loadingKiosk = false
                entry.loading = false
                entry.editDetails = false
            },
            createOverride: function(entries) {
                let title = "Manual Kiosk Override"
                kioskService.ctrlData.currentOverride = {}
                kioskService.ctrlData.currentOverrides = entries
                if (entries.length == 1) {
                    kioskService.ctrlData.currentOverride = entries[0]
                    if (kioskService.ctrlData.currentOverride.dateStartOverride) {
                        kioskService.ctrlData.currentOverride.dateStartOverride = kioskService.ctrlData.currentOverride.dateStartOverrideJS.toLocaleDateString()
                        kioskService.ctrlData.currentOverride.dateEndOverride = kioskService.ctrlData.currentOverride.dateEndOverrideJS.toLocaleDateString()
                    }
                    title += ` - ${entries[0].lastfirst}`
                } else {
                    title += ` - ${entries.length} Students`
                }

                let psDialogHolder = null
                psDialogHolder = $j("#idMKioskManualDialog")

                psDialog({
                    id: "kioskManualDialog",
                    title: title,
                    content: psDialogHolder,
                    type: "dialogM",
                    close: function() {
                        $j('#idMFOTMDialogHolder').append(psDialogHolder);
                    },
                    buttons: [
                        {
                            id: "cancelButton",
                            text: "Cancel",
                            click: function() {
                                kioskService.ctrlData.currentOverride = {}
                                kioskService.ctrlData.currentOverrides = []
                                psDialogClose()
                            }
                        },
                        {
                            id: "confirmButton",
                            text: "Confirm",
                            click: function() {
                                loadingDialog()
                                let saveEntries = kioskService.ctrlData.currentOverrides.length
                                let savedEntries = 0
                                kioskService.ctrlData.currentOverrides.forEach(function(entry) {
                                    kioskService.saveOverride(entry).then(function() {
                                        savedEntries++
                                        if (savedEntries == saveEntries) {
                                            kioskService.validateAll(true)
                                            closeLoading()
                                        }
                                    })
                                })
                                psDialogClose()
                            }
                        }
                    ]
                })
            },
            saveOverride: function(entry) {
                let overrideAuth = forms.read("#idmFOTMKioskOverrideAuth input")
                let submitObj = {
                    ac: "prim",
                    frn: `001${entry.studentsdcid}`
                }
                Object.keys(overrideAuth).forEach(function(key) {
                    let useName = overrideAuth[key].name
                    if (entry.idOverride) {
                        useName = useName.replace("-99", entry.idOverride)
                    }
                    if (entry[key]) {
                        submitObj[useName] = entry[key]
                    }
                    if (kioskService.ctrlData.currentOverride[key]) {
                        submitObj[useName] = kioskService.ctrlData.currentOverride[key]
                    }
                })
                return $http({
                    url: `/admin/attendance/functions/idm_helper.html?helperType=changesRecorded`,
                    method: "POST",
                    data: $httpParamSerializer(submitObj),
                    headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                })
                
            },
            loadKiosk: function(entry) {
                kioskService.ctrlData.kioskEntriesPrevious = _.pluck(kioskService.ctrlData.kioskEntries, "kioskid")
                
                if (!window.location.href.includes("idm_kioskReport.html")) {
                    loadingDialog(pss_text('psx.htmlc.idmFOTM.loading'), "identimetricsFOTMReport")
                } else {
                    kioskService.ctrlData.loadingKiosk = true
                }

                let params = {}
                params.dateStart = kioskService.ctrlData.args.isoFormat(new Date(kioskService.ctrlData.reportControls.dateStart))
                params.dateEnd = kioskService.ctrlData.args.isoFormat(new Date(kioskService.ctrlData.reportControls.dateEnd))
                
                if (entry) {
                    params.kioskid = entry.kioskid
                }

                $http({
                    url: "/admin/attendance/functions/idm_helper.html?helperType=kioskData",
                    method: "GET",
                    params: params,
                    headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
                }).then(function(response) {
                    response.data.pop()
                    response.data.forEach(function(rec) {
                        rec.scanResult = kioskService.ctrlData.map.scanResultsInverted[rec.scanCode]
                        if (rec.resolvedResultCode != "") {
                            rec.resolvedResult = kioskService.ctrlData.map.scanResultsInverted[rec.resolvedResultCode]
                        }
                    })
                    if (!entry) {
                        kioskService.ctrlData.kioskEntries = response.data
                        kioskService.ctrlData.kioskEntries.forEach(function(entry) {
                            entry.scanDateJS = new Date(`${entry.scanDate}T00:00:00`)
                            entry.scanDateJSend = new Date(`${entry.scanDate}T00:00:00`)
                        })
                        kioskService.ctrlData.kioskErrors = _.filter(kioskService.ctrlData.kioskEntries, function(rec) {
                            return rec.resolved == "0" && ((rec.scanCode < 0 && rec.resolvedResultCode == "") || (rec.resolvedResultCode != "" && rec.resolvedResultCode < 0))

                        })
                        kioskService.ctrlData.kioskAllowed = _.filter(kioskService.ctrlData.kioskEntries, function(rec) {
                            return (rec.scanCode > 0 && rec.resolvedResultCode == "") || rec.resolved == "1"
                        })
                        kioskService.ctrlData.countdown = 5
                        closeLoading()
                        kioskService.ctrlData.loadingKiosk = false
                        kioskService.ctrlData.ticker = new Date()
                        kioskService.ctrlData.kioskLastUpdated = (new Date()).toLocaleTimeString()
                        kioskService.ctrlData.kioskUpdateCount++
                    } else {
                        let existRec = _.findIndex(kioskService.ctrlData.kioskEntries, {kioskid: entry.kioskid})
                        if (existRec > -1) {
                            kioskService.ctrlData.kioskEntries[existRec] = response.data[0]
                            kioskService.ctrlData.kioskErrors = _.filter(kioskService.ctrlData.kioskEntries, function(rec) {
                                return rec.scanCode < 0 && rec.resolved == "0"
                            })
                            kioskService.ctrlData.kioskAllowed = _.filter(kioskService.ctrlData.kioskEntries, function(rec) {
                                return rec.scanCode > 0 || rec.resolved == "1"
                            })
                        }
                        kioskService.ctrlData.loadingKiosk = false
                    }
                })
            }
        }

        return kioskService
	}])
});