'use strict';
define(function(require) {
    let module = require('components/identimetricsFOTM/module');
    module.controller('users', ['$scope', '$rootScope', '$http', '$httpParamSerializer', '$q', '$timeout', '$sce',  'forms', 'idMService', function($scope, $rootScope, $http, $httpParamSerializer, $q, $timeout, $sce, forms, idMService) {
        idMService.init()
        $scope.idMService = idMService
        console.log($scope)
        let PaginationHelper = require('components/widgets/models/PaginationHelperWithFilterTracking')
        $scope.ctrlData = {
            args: idmFOTMArgs,
            map: idMService.map,
            gwCtrlData: idMService.gwCtrlData,
            users: [],
            schoolUsers: [],
            newUsers: [],
            errorUsers: [],
            missingFields: []
        }
        idMService.ctrlData = $scope.ctrlData
        $scope._ = _
        $scope.true = true
        $scope.false = false
        $scope.undefined = undefined
        $scope.handSelected = []
        $scope.massEdit = {
            defaultCode: "",
            kioskCodeOptions: [],
            kioskPopupInformation: [],
            kioskDenialReasons: [],
            noAttendanceRecord: "",
            kioskUser: "",
        }
        $scope.displayMissing = false
        $scope.displayErrors = false
        $scope.requiredTemplateFields = ["first_name","last_name","teachernumber","loginid","password","schoolid"]
        $scope.uniqueFields = ["teachernumber", "loginid", "idpID"]
        $scope.templateModified = false
        $scope.baseTemplate = {
            count: 1,
            startIndex: 1,
            first_name: "idM",
            last_name: "Kiosk ?",
            teachernumber: "idM_Kiosk?",
            email_addr: "",
            idpID: "",
            schoolid: "",
            group: "1",
            canChangeSchool: [],
            loginid: "idmKiosk?",
            password: "idmKiosk1!",
            staffstatus: "0",
            defaultCode: "",
            kioskUser: "0",
            kioskCodeOptions: ["default"],
            kioskPopupInformation: ["default"],
            kioskDenialReasons: ["default"],
            noAttendanceRecord: "0"
        }
        if ($scope.ctrlData.args.curschoolid != "0") {
            $scope.baseTemplate.schoolid = $scope.ctrlData.args.curschoolid
        }
        $scope.multiFields = ["kioskCodeOptions","kioskPopupInformation","kioskDenialReasons"]

        $scope.pgController = new PaginationHelper()
        
        $scope.resetUserTemplate = function() {
            $scope.userTemplate = _.clone($scope.baseTemplate)
            
            $scope.ctrlData.newUsers = []
            $scope.missingFields = []
            $scope.ctrlData.errorUsers = []
            $scope.overlapLoginid = []
            $scope.overlapTeachernumber = []
            $scope.overlapIDP = []
        }
        $scope.resetUserTemplate()

        $scope.$watch("userTemplate", function() {
            if ($scope.ctrlData.users.length > 0) {
                if (_.isEqual($scope.baseTemplate, $scope.userTemplate)) {
                    $scope.templateModified = false
                } else {
                    $scope.testTemplate()
                }
            }
        }, true)

        $scope.$watch("ctrlData.filteredUsers", function() {
            $j("table.idm_userTable tr").each(function(i, e) {
                $j(e).find("th.idm_userInfo:first").addClass("idm_borderLeftStrong")
                $j(e).find("th.idm_userInfo:last").addClass("idm_borderRightStrong")
                $j(e).find("th.idm_officeInfo:first").addClass("idm_borderLeftStrong")
                $j(e).find("th.idm_officeInfo:last").addClass("idm_borderRightStrong")
                $j(e).find("th.idm_kioskInfo:first").addClass("idm_borderLeftStrong")
                $j(e).find("th.idm_kioskInfo:last").addClass("idm_borderRightStrong")
                $j(e).find("td.idm_userInfo:first").addClass("idm_borderLeftStrong")
                $j(e).find("td.idm_userInfo:last").addClass("idm_borderRightStrong")
                $j(e).find("td.idm_officeInfo:first").addClass("idm_borderLeftStrong")
                $j(e).find("td.idm_officeInfo:last").addClass("idm_borderRightStrong")
                $j(e).find("td.idm_kioskInfo:first").addClass("idm_borderLeftStrong")
                $j(e).find("td.idm_kioskInfo:last").addClass("idm_borderRightStrong")
            })
        }, true)

        $scope.rangeCount = function(start, count) {
            let retArr = []
            for (let i=start;i<start+count;i++) {
                retArr.push(i)
            }
            return retArr
        }

        $scope.exportCSV = function() {
            loadingDialog( `Exporting entries` );
            let entries
            if ($scope.handSelected.length == 0) {
                entries = $scope.pgController.filteredItemsAllPages
            } else {
                entries = $scope.handSelected
            }
            
            let today = new Date;

            let data = [[]]

            Object.keys(entries[0]).forEach(function(key) {
                if (key != "$$hashKey") {
                    data[0].push(key)
                }
            })

            entries.forEach(function(entry) {
                let entryArr = []
                data[0].forEach(function(key) {
                    entryArr.push(entry[key])
                })
                data.push(entryArr)
            })

            data = (
                _.chain(data)
                .map( entry=>{ return entry.join('\t') } )
                .value()
                .join('\r\n')
            );

            let blob = new Blob([data], {type: "text/plain;charset=utf-8"});

			saveAs(blob, "Current Users " + today.getFullYear() + "-" + ("0" + (today.getMonth() + 1)).slice(-2) + "-" + ("0" + today.getDate()).slice(-2) + " " + ("0" + today.getHours()).slice(-2) + ("0" + today.getMinutes()).slice(-2) + ("0" + today.getSeconds()).slice(-2) + ".txt");

            closeLoading();
        }

        $scope.toggleFieldValue = function(target, field, value, defaultEmpty) {
            if (target[field].includes(value)) {
                target[field] = _.without(target[field], value)
                if (target[field].length == 0 && !defaultEmpty) {
                    target[field].push("default")
                }
            } else {
                target[field].push(value)
                if (target[field].includes("default") && !defaultEmpty) {
                    target[field] = _.without(target[field], "default")
                }
            }
        }

        $scope.selectUsers = function() {
            let teachersdcids = _.pluck($scope.handSelected, "teachersdcid")
            $http({
                url: `/admin/facultylist/functions.html?ac=buildsel;table=teachers;list=${teachersdcids.join(",")}`,
                method: "GET"
            }).then(function() {
                window.open("/admin/facultylist/functions.html")
            })
        }

        $scope.toggleEdit = function(user) {
            if (user.edit) {
                delete user.edit
            } else {
                user.edit = {
                    defaultCode: user.defaultCode,
                    kioskCodeOptions: user.kioskCodeOptions,
                    kioskPopupInformation: user.kioskPopupInformation,
                    kioskDenialReasons: user.kioskDenialReasons,
                    noAttendanceRecord: user.noAttendanceRecord,
                    kioskUser: user.kioskUser
                }
            }
        }

        $scope.massDialog = function() {
            $scope.massEdit = {
                defaultCode: "",
                kioskCodeOptions: [],
                kioskDenialReasons: [],
                noAttendanceRecord: "",
                kioskUser: "",
            }
            var psDialogHolder = $j("#idmAutoTardyMassSetting").detach()

            psDialog({
                content: psDialogHolder,
                type: "dialogM",
                title: "Mass Edit Selected",
                close: function() {
                    $j("#idMFOTMDialogHolder").append(psDialogHolder)
                },
                buttons: [
                    {
                        id: "cancelButton",
                        text: "Cancel",
                        click: function() {
                            psDialogClose()
                        }
                    },
                    {
                        id: "confirmButton",
                        text: "Confirm",
                        click: function() {
                            $scope.setFields($scope.massEdit, $scope.handSelected)
                            psDialogClose()
                        }
                    }
                ]
            })
        }

        $scope.createUserTemplate = function() {
            $scope.resetUserTemplate()
            var psDialogHolder = $j("#idmAutoTardyUserTemplate").detach()

            psDialog({
                content: psDialogHolder,
                type: "dialogM",
                docked: "east",
                title: "User Creation Template",
                close: function() {
                    $j("#idMFOTMDialogHolder").append(psDialogHolder)
                },
                buttons: [
                    {
                        id: "cancelButton",
                        text: "Cancel",
                        click: function() {
                            $scope.resetUserTemplate()
                            psDialogClose()
                        }
                    },
                    {
                        id: "createButton",
                        text: "Create",
                        click: function() {
                            $scope.testTemplate(true, true)
                        }
                    }
                ]
            })
        }

        $scope.testTemplate = function(fullTest, submitTemplate) {
            $scope.templateModified = true
            $scope.ctrlData.newUsers = []
            $scope.missingFields = []
            $scope.ctrlData.errorUsers = []
            $scope.overlapLoginid = []
            $scope.overlapTeachernumber = []
            $scope.overlapIDP = []
            $scope.requiredTemplateFields.forEach(function(field) {
                if ($scope.userTemplate[field] === "" || $scope.userTemplate[field] === null) {
                    $scope.missingFields.push(field)
                }
            })

            if (fullTest && $scope.missingFields.length > 0) {
                $scope.displayMissing = true
                $scope.$apply()
            } else {
                $scope.displayMissing = false
            }

            for (let i=$scope.userTemplate.startIndex;i<$scope.userTemplate.startIndex+$scope.userTemplate.count;i++) {
                let newUser = _.clone($scope.userTemplate)
                newUser.index = i
                for (const [key, val] of Object.entries($scope.userTemplate)) {
                    if (typeof(val) == "string") {
                        newUser[key] = val.replaceAll("\?", i)
                    } else {
                        newUser[key] = val
                    }
                }

                $scope.ctrlData.newUsers.push(newUser)
                $scope.ctrlData.users.forEach(function(existUser) {
                    if (
                        newUser.loginid.toLowerCase() == existUser.loginid.toLowerCase() || 
                        newUser.teachernumber.toLowerCase() == existUser.teachernumber.toLowerCase() ||
                        (newUser.idpID != "" && newUser.idpID.toLowerCase() == existUser.idpID.toLowerCase())
                    ) {
                        if (newUser.loginid.toLowerCase() == existUser.loginid.toLowerCase()) {
                            $scope.overlapLoginid.push(existUser.loginid)
                        }
                        if (newUser.teachernumber.toLowerCase() == existUser.teachernumber.toLowerCase()) {
                            $scope.overlapTeachernumber.push(existUser.teachernumber)
                        }
                        if (newUser.idpID != "" && newUser.idpID.toLowerCase() == existUser.idpID.toLowerCase()) {
                            $scope.overlapIDP.push(existUser.idpID)
                        }
                        $scope.ctrlData.errorUsers.push({
                            newUser: newUser,
                            existUser: existUser
                        })
                    }
                })
            }
            if ($scope.missingFields.length == 0 && $scope.ctrlData.errorUsers.length == 0) {
                angular.element("#createButton").removeClass("disabled")
                if (submitTemplate) {
                    $scope.confirmCreate()
                }
            } else {
                angular.element("#createButton").addClass("disabled")
            }
        }

        $scope.confirmCreate = function() {
            var psDialogHolderConfirm = $j("#idmAutoTardyUserConfirm").detach()

            psDialog({
                content: psDialogHolderConfirm,
                type: "dialogM",
                title: `Confirm Create ${$scope.ctrlData.newUsers.length} Users`,
                close: function() {
                    $j("#idMFOTMDialogHolder").append(psDialogHolderConfirm)
                },
                buttons: [
                    {
                        id: "cancelButton",
                        text: "Cancel",
                        click: function() {
                            psDialogClose($j('#psDialog'))
                        }
                    },
                    {
                        id: "confirmButton",
                        text: "Confirm",
                        click: function() {
                            $scope.createUsers()
                            psDialogClose()
                        }
                    }
                ]
            })
        }
        
        $scope.createUsers = function() {
            loadingDialog()
            let completedCount = 0
            $scope.ctrlData.newUsers.forEach(function(newUser) {
                let submitObj = forms.read("#idm_newUserAuth input")

                for (const [key, val] of Object.entries(newUser)) {
                    if (Object.keys(submitObj).includes(key)) {
                        submitObj[key].value = val
                    } 
                }

                if (!submitObj.canChangeSchool.value.includes(submitObj.schoolid.value)) {
                    submitObj.canChangeSchool.value.push(submitObj.schoolid.value)
                }

                submitObj.homeschoolid.value = submitObj.schoolid.value
                submitObj.canChangeSchoolArr = {
                    name: "canChangeSchoolArr",
                    value: submitObj.canChangeSchool.value
                }
                submitObj.canChangeSchool.value = submitObj.canChangeSchool.value.join(";")
                submitObj.teachernumberQ = {
                    name: "teachernumber",
                    value: submitObj.teachernumber.value
                }
                submitObj.legacyAdminPW = {
                    name: "user.legacyAdminPW",
                    value: submitObj.password.value
                }

                if (newUser.idpID) {
                    submitObj.idpID = {
                        name: "idpID",
                        value: newUser.idpID
                    }
                }

                forms.saveNewUser(submitObj).then(function(response) {
                    let form = forms.read(response.data)

                    $scope.setInitialPassword(submitObj, form.teachersdcid.value).then(function() {
                        delete form.frn
                        for (const [key, val] of Object.entries(newUser)) {
                            if (Object.keys(form).includes(key)) {
                                form[key].value = val
                            } 
                        }
    
                        forms.save(form).then(function() {
                            completedCount++
                            if (completedCount == $scope.userTemplate.count) {
                                $scope.getUsers()
                            }
                        })
                    })

                })
            })
        }

        $scope.setInitialPassword = function(user, teachersdcid) {
            let formData = {
                "user.adminAccess": "1",
                "user.loginId": user.loginid ? user.loginid.value : "",
                "user.legacyAdminPW": user.password ? user.password.value : "",
                "commonUser.openIdUserAccountId": user.idpID ? user.idpID.value : "",
                "user.groupId": user.group ? user.group.value : "",
                "NoTimeRestrictions": "on",
                "user.allowLoginStartString": "",
                "user.allowLoginEndString": "",
                "savedAllowLoginStart": "",
                "savedAllowLoginEnd": "",
                "user.ipAddrRestrict": "",
                "frn": `005${teachersdcid}`,
                "homeSchoolId": user.schoolid ? user.schoolid.value : "",
                "jsonRequestString": JSON.stringify(_.map(user.canChangeSchoolArr.value, function(school) {
                    return {
                        "schoolNumber": school,
                        "roleId": "-1"
                    }
                }))
            }

            return $http({
                url: "/admin/faculty/saveAssociations.action",
                method: "POST",
                data: $httpParamSerializer(formData),
                headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
            })
        }

        $scope.handSelect = function(userArr) {
            if (userArr.length == $scope.pgController.filteredItemsAllPages.length) {
                if ($scope.handSelected.length == userArr.length) {
                    $scope.handSelected = []
                } else {
                    userArr.forEach(function(user) {
                      if (!$scope.handSelected.includes(user)) {
                        $scope.handSelected.push(user)
                      }
                    })
                }
            } else {
                userArr.forEach(function(user) {
                    if ($scope.handSelected.includes(user)) {
                        $scope.handSelected = _.without($scope.handSelected, user)
                    } else {
                        $scope.handSelected.push(user)
                    }
                })
            }
        }

        $scope.setFields = function(newVals, users) {
            loadingDialog()
            let i = 0
            users.forEach(function(user) {
                for (const [key, value] of Object.entries(newVals)) {
                    if (typeof(value) == "string") {
                        if (value == "default") {
                            user[key] = ""
                        } else if (value !== "") {
                            user[key] = value
                        }
                    }
                    if (Array.isArray(value)) {
                        if (value.length > 0) {
                            if (value[0] == "default") {
                                user[key] = ""
                            } else {
                                user[key] = value
                            }
                        }
                    }
                }
                let authObj = {frn: `204${user.usersdcid}`}
                $http({
                    method: "GET",
                    params: authObj,
                    url: "/admin/attendance/functions/idm_helper.html?helperType=userAuth"
                }).then(function(response) {
                    let form = forms.read(response.data)
                    for (const [key, value] of Object.entries(newVals)) {
                        if (typeof(value) == "string") {
                            if (value == "default") {
                                form[key].value = ""
                            } else if (value !== "") {
                                form[key].value = value
                            }
                        }
                        if (Array.isArray(value)) {
                            if (value.length > 0) {
                                if (value[0] == "default") {
                                    form[key].value = ""
                                } else {
                                    form[key].value = value
                                }
                            }
                        }
                    }
                    forms.save(form).then(function() {
                        i++
                        delete user.edit
                        if (i == users.length) {
                            $scope.getUsers()
                        }
                    })
                })
            })   
        }

        $scope.getUsers = function() {
            loadingDialog()
            $http({
                method: "GET",
                url: "/admin/attendance/functions/idm_helper.html?helperType=userData",
                params: {}
            }).then(function(response) {
                response.data.pop()
                response.data.forEach(function(user) {
                    $scope.multiFields.forEach(function(multiField) {
                        user[multiField] = _.compact(user[multiField].split(","))
                    })
                })
                $scope.ctrlData.users = response.data
                $scope.ctrlData.schoolUsers = _.filter($scope.ctrlData.users, function(user) {
                    return $scope.ctrlData.args.curschoolid == "0" || user.homeschoolid == $scope.ctrlData.args.curschoolid
                })
                closeLoading()
            })
        }

        $scope.getUsers()
        
        if (idm_schools) {
            $scope.schools = idm_schools
        }
        
        if (idm_groups) {
            $scope.groups = idm_groups
        }

        if (idm_attCodes) {
            $scope.attCodes = idm_attCodes
        }
        
        if (idm_attCodesKiosk) {
            $scope.attCodesKiosk = idm_attCodesKiosk
        }

        // Check ez-update status
        $scope.auth = true;
        
        idmxTdyAuth().then(r => {
            $scope.auth = r;
        });
    }]);
});