'use strict';
define(function(require) {
	let module = require('components/identimetricsFOTM/module');
	module.factory('idMService', ['$http', '$httpParamSerializer', '$timeout', '$filter', '$rootScope', function($http, $httpParamSerializer, $timeout, $filter, $rootScope) {
        pss_get_texts("psx.htmlc.idmFOTM")
        var idMService = {
            gwCtrlData: {},
            init: function() {
                setInterval(function() {
                    $timeout(function() {
                        idMService.ctrlData.ticker = new Date()
                    })
                }, 1000)
            },
			exportCSV: function(records, fields, fieldTitles, name) {
                var today = new Date()
                var contents = ""
                contents += fieldTitles.join("\t") + "\r\n"
                contents += _.map(records, function(row) {
                    var baseArr = []
                    baseArr = _.map(fields, function(field) {
                        var dataField = row[field]
                        if (["string","number"].includes(typeof(dataField))) {
                            return '' + dataField + ''
                        } else if (Array.isArray(dataField) && typeof(dataField[0]) == "string") {
                            return '' + dataField.join(",") + ''
                        } else {
                            return ""
                        }
                    })
                    return baseArr.join("\t")
                }).join("\r\n")

                var blob = new Blob([contents], {type: "text/plain;charset=utf-8"});
                saveAs(blob, `${name}.txt`);    
            },
            buildSel: function(students, field) {
                loadingDialog( `Selecting students` );
                let ids = _.pluck(students, field)

                let obj = $httpParamSerializer({
                    ids: ids,
                    forward: "/admin/home.html",
                    selectionAction: "replace"
                })

                $http.post("/admin/SaveSelectedStudentsToSelection.action", obj, {"headers": {"Content-Type": "application/x-www-form-urlencoded"}})
                    .then(function() {
                        closeLoading();
                        window.open("/admin/home.html");
                })
            },
            prepareTime: function(entry, dateObj) {
                let timeData = {
                    "useTime": dateObj,
                    "att_date": idMService.ctrlData.args.isoFormat(dateObj),
                    "submitHour24": dateObj.getHours(),
                    "submitHour24Pad": dateObj.getHours(),
                    "submitMinute": dateObj.getMinutes(),
                    "submitMinutePad": dateObj.getMinutes(),
                    "timeString": "",
                    "timeStringPad": "",
                    "timeString24": "",
                    "timeString24Pad": "",
                    "firstTime": dateObj
                }
                if (entry.timeData) {
                    timeData.firstTime = entry.timeData.firstTime
                }
                timeData.submitHour12 = ((timeData.submitHour24 + 11) % 12 + 1)
                timeData.submitHour12Pad = timeData.submitHour12
                if (timeData.submitHour24 < 10) {
                    timeData.submitHour24Pad = String(timeData.submitHour24).padStart(2, "0")
                }
                if (timeData.submitHour12 < 10) {
                    timeData.submitHour12Pad = String(timeData.submitHour12).padStart(2, "0")
                }
                if (timeData.submitMinute < 10) {
                    timeData.submitMinutePad = String(timeData.submitMinute).padStart(2, "0")
                }
                timeData.submitMeridian = timeData.submitHour24 >= 12 ? "PM" : "AM"
                timeData.timeString = `${timeData.submitHour12}:${timeData.submitMinutePad} ${timeData.submitMeridian}`
                timeData.timeStringPad = `${timeData.submitHour12Pad}:${timeData.submitMinutePad} ${timeData.submitMeridian}`
                timeData.timeString24 = `${timeData.submitHour24}:${timeData.submitMinutePad}`
                timeData.timeString24Pad = `${timeData.submitHour24Pad}:${timeData.submitMinutePad}`
                timeData.timeSeconds = timeData.submitHour24*60*60 + timeData.submitMinute*60

                return timeData
            },
            map: {
                yesno: {},
                yesno2: {},
                yesno3: {},
                codes: {},
                codeTypes: {
                    "Tardy": "T",
                    "Excused Tardy": "TE",
                    "Unexcused Tardy": "TU"
                },
                scanResults: {
                    "Allowed": "1",
                    "Warning": "0",
                    "Denied - No Student Found": "-1",
                    "Denied - Different School": "-2",
                    "Denied - Attendance": "-3",
                    "Denied - Enrollment": "-4",
                    "Denied - No Membership": "-5",
                    "Denied - Repeated Scan": "-6",
                    "Denied - Other": "-100",
                    "None": "none"
                },
                resolveResults: {
                    "Allowed ": "1",
                    "Warning ": "0",
                    "Denied - No Student Found ": "-1",
                    "Denied - Different School ": "-2",
                    "Denied - Attendance ": "-3",
                    "Denied - Enrollment ": "-4",
                    "Denied - No Membership ": "-5",
                    "Denied - Repeated Scan ": "-6",
                    "Denied - Other ": "-100",
                    "None ": "none"
                },
                overrideResults: {
                    "Allowed  ": "1",
                    "Warning  ": "0",
                    "Denied - No Student Found  ": "-1",
                    "Denied - Different School  ": "-2",
                    "Denied - Attendance  ": "-3",
                    "Denied - Enrollment  ": "-4",
                    "Denied - No Membership  ": "-5",
                    "Denied - Repeated Scan  ": "-6",
                    "Denied - Other  ": "-100",
                    "None  ": "none"
                },
                popupInformation: {
                    "Student Photo": "photo",
                    "Student Name": "name", 
                    "Denial Reason": "reason",
                    "Student Identifier": "number",
                    "None": "none"
                },
                schools: {"District Office": "0"},
                groups: {},
                codeTypesInverted: {},
                schoolsInverted: {"0": "District Office"},
                scanResultsInverted: {},
                resolveResultsInverted: {},
                popupInformationInverted: {},
                overrideResultsInverted: {},
                groupsInverted: {}
            }
		}

        idMService.map.yesno[pss_text("psx.js.scripts.psbehaviors.yes")] = "1"
        idMService.map.yesno[pss_text("psx.js.scripts.psbehaviors.no")] = "0"
        idMService.map.yesno2[`${pss_text("psx.js.scripts.psbehaviors.yes")} `] = "1"
        idMService.map.yesno2[`${pss_text("psx.js.scripts.psbehaviors.no")} `] = "0"
        idMService.map.yesno3[`${pss_text("psx.js.scripts.psbehaviors.yes")}  `] = "1"
        idMService.map.yesno3[`${pss_text("psx.js.scripts.psbehaviors.no")}  `] = "0"

        if (idmFOTMArgs) {
            idmFOTMArgs.schools.forEach(function(school) {
                idMService.map.schools[school.name] = school.schoolid
            })
            idmFOTMArgs.groups.forEach(function(group) {
                idMService.map.groups[group.name] = group.number
            })
        }

        for (const [key, value] of Object.entries(idMService.map)) {
            if (key.includes("Inverted")) {
                let originalKey = key.replace("Inverted","")
                for (const [orig_key, orig_value] of Object.entries(idMService.map[originalKey])) {
                    idMService.map[key][orig_value] = orig_key
                }
            }
        }

        return idMService
	}])

    module.config(function($provide) {
        $provide.decorator('pssGridWidgetDirective', function($delegate, idMService) {
            var directive = $delegate[0]
            var compile = directive.compile
            directive.compile = function(elements, attributes) {
                var link = compile.apply(this, arguments)
                return function(scope, elem, attrs) {
                    link.apply(this, arguments)
                    idMService.gwCtrlData[`gridScope_${attrs.data}`] = scope
                }
            }
            return $delegate
        })
    })
});