'use strict';
define(function(require) {
    let module = require('components/identimetricsFOTM/module');
    module.controller('config', ['$scope', '$rootScope', '$http', '$httpParamSerializer', '$q', '$timeout',  'forms', 'idMService', function($scope, $rootScope, $http, $httpParamSerializer, $q, $timeout, forms, idMService) {
        console.log($scope)
        $scope.idMService = idMService
        pss_get_texts("psx.htmlc.idmFOTM")

        $scope.Math = Math
        
        $scope.ctrlData = {
            init: function() {
                // Read results of PSHTML tags into object
                $scope.ctrlData.pshtml = forms.read( '#pshtml :input' );

                // Read current settings into form
                $scope.ctrlData.form = forms.read( '#settings :input' );
                let defaultSettings = [
                    {
                        "pref": "idm_tardyCommentMaximum",
                        "value": 50
                    },
                    {
                        "pref": "idm_tardyExcusedCommentMaximum",
                        "value": 50
                    },
                    {
                        "pref": "idm_tardyUnexcusedCommentMaximum",
                        "value": 50
                    },
                    {
                        "pref": "idm_exceptionOverlap",
                        "value": ""
                    },
                    {
                        "pref": "idm_exceptionMultiSection",
                        "value": ""
                    },
                    {
                        "pref": "idm_exceptionNoClass",
                        "value": ""
                    },
                    {
                        "pref": "idm_kioskDurationWelcome",
                        "value": 3
                    },
                    {
                        "pref": "idm_kioskDurationError",
                        "value": 3
                    },
                    {
                        "pref": "idm_kioskDenyRecentMinutes",
                        "value": 0
                    },
                    {
                        "pref": "idm_kioskDenialReasons",
                        "value": ["-1","-2","-3","-4","-5","-6"]
                    }
                ]
                let numberFields = ["idm_tardyCommentMaximum", "idm_tardyExcusedCommentMaximum", "idm_tardyUnexcusedCommentMaximum", "idm_kioskDurationWelcome", "idm_kioskDurationError", "idm_kioskDenyRecentMinutes"]
                let multipleFields = ["idm_exceptionOverlapPeriods", "idm_exceptionMultiSectionCourses","idm_kioskPopupInformation","idm_kioskDenialReasons"]
                defaultSettings.forEach(function(setting) {
                    if ($scope.ctrlData.form[setting.pref]) {
                        if ($scope.ctrlData.form[setting.pref].value == "") {
                            $scope.ctrlData.form[setting.pref].value = setting.value
                        }
                    }
                })
                numberFields.forEach(function(field) {
                    $scope.ctrlData.form[field].value = parseInt($scope.ctrlData.form[field].value)
                })
                multipleFields.forEach(function(field) {
                    if (typeof($scope.ctrlData.form[field].value) == "string") {
                        $scope.ctrlData.form[field].value = $scope.ctrlData.form[field].value.split(",")
                        $scope.ctrlData.form[field].value.forEach(function(val, i) {
                            if (val === "") {
                                $scope.ctrlData.form[field].value.splice(i, 1)
                            }
                        })
                    }
                })

                if ($scope.ctrlData.pshtml.level.value == 'school') {
                    $scope.ctrlData.districtSettings = forms.read( '#districtSettings :input' );
                    defaultSettings.forEach(function(setting) {
                        if ($scope.ctrlData.districtSettings[setting.pref]) {
                            if ($scope.ctrlData.districtSettings[setting.pref].value == "") {
                                $scope.ctrlData.districtSettings[setting.pref].value = setting.value
                            }
                        }
                    })
                    numberFields.forEach(function(field) {
                        $scope.ctrlData.districtSettings[field].value = parseInt($scope.ctrlData.districtSettings[field].value)
                    })
                    multipleFields.forEach(function(field) {
                        if (typeof($scope.ctrlData.districtSettings[field].value) == "string") {
                            $scope.ctrlData.districtSettings[field].value = $scope.ctrlData.districtSettings[field].value.split(",")
                            $scope.ctrlData.districtSettings[field].value.forEach(function(val, i) {
                                if (val === "") {
                                    $scope.ctrlData.districtSettings[field].value.splice(i, 1)
                                }
                            })
                        }
                    })
                }

                // Reorganize attendance codes into code/description pairs
                $scope.ctrlData.pshtml.attendanceCodes = (
                    _.chain( angular.element("#attendanceCodes attendanceCode") )
                    .map( a=>{
                        let element = angular.element(a);
                        return [
                            element.attr('code'),
                            element.text()
                        ]
                    } )
                    .object()
                    .value()
                );

                // Reorganize term lengths into portion/description pairs
                $scope.ctrlData.pshtml.termLengths = (
                    _.chain( angular.element("#termLengths termlength") )
                    .map( t=> {
                        let element = angular.element(t);
                        return {
                            portion: element.attr('portion'),
                            description: element.text()
                        }
                    } )
                    .value()
                )

                // Reorganize periods into period_number/description pairs
                $scope.ctrlData.pshtml.periods = (
                    _.chain( angular.element("#periods period") )
                    .map( t=> {
                        let element = angular.element(t);
                        return {
                            period_number: element.attr('period_number'),
                            description: element.text()
                        }
                    } )
                    .value()
                )

                // Reorganize periods into course_number/course_name pairs
                $scope.ctrlData.pshtml.courses = (
                    _.chain( angular.element("#courses course") )
                    .map( t=> {
                        let element = angular.element(t);
                        return {
                            course_number: element.attr('course_number'),
                            course_name: element.text()
                        }
                    } )
                    .value()
                )
                
                //Number of tardy comments per category?
                //Needs to be a pref, but default to 0, max 50
                $scope.ctrlData.tardyComments = 50;
                $scope.ctrlData.commentRange = [];
                for (let i=1; i<=$scope.ctrlData.tardyComments; i++) {
                    $scope.ctrlData.commentRange.push(i);
                }

                // Check ez-update status
                $scope.ctrlData.auth = true;

                idmxTdyAuth().then(r => {
                    $scope.ctrlData.auth = r;
                });
            },
            map: idMService.map,
            bindCoursePicker: function() {
                $j('#idm_coursePicker').bind('keydown', $scope.ctrlData.autoComplete.keyBinding).autocomplete({
                    close: $scope.ctrlData.autoComplete.close,
                    focus: $scope.ctrlData.autoComplete.focus,
                    minLength: 1,
                    open: $scope.ctrlData.autoComplete.openCoursePicker,
                    select: $scope.ctrlData.autoComplete.selectCourse,
                    source: $scope.ctrlData.autoComplete.coursePickerResponse
                })
            },

            autoComplete: {
                close: function () {
                    $j(this).removeClass('ui-corner-top').addClass('ui-corner-all');
                },
                focus: function () {
                    return false;
                },
                keyBinding: function (event) {
                    if (event.keyCode === $j.ui.keyCode.TAB &&
                        $j(this).autocomplete('instance').menu.active) {
                        event.preventDefault();
                    }
                },
                selectCourse: function (event, ui) {
                    var terms = $scope.ctrlData.split(this.value);

                    terms.pop();
                    terms.push(ui.item.value);
                    terms.push('');
                    this.value = terms.join(', ');

                    return false;
                },
                coursePickerResponse: 
                    function (request, response) {
                        if (request.term) {
                            $scope.ctrlData.courseResource.getCoursesLike($scope.ctrlData.extractLast(request.term)).then(
                                function (results) {
                                    results.data = results.data.slice(0, $scope.ctrlData.autoComplete.maxResults - 1);

                                    _.each(
                                        results.data,
                                        function (result) {
                                            result.id = result._id;
                                            result.label = '(' + result.course_number + ') ' + result.course_name;
                                            result.value = result.course_number;
                                        }
                                    );

                                    response(results.data);
                                }
                            );
                        }
                    },
                    openCoursePicker: function(event, ui) {
                        $j(this).removeClass('ui-corner-all').addClass('ui-corner-top');
                        var widgetItems = $j('#idm_coursePicker').autocomplete('widget').children();
                        
                        for(var i = 0; i < widgetItems.length; i++) {
                            $j(widgetItems[i]).attr('id', 'course-autocomplete-' + i);
                        }
                    },
                    maxResults: 50
            },
            extractLast: function (term) {
                return $scope.ctrlData.split(term).pop();
            },
            split: function (val) {
                if (typeof val === 'string') {
                    return val.split(/,\s*/);
                } else {
                    return [];
                }
            },
            // Save settings
            save: function() {
                loadingDialog("Saving", "idm_saving");

                forms.save( $scope.ctrlData.form ).then(function(){
                    closeLoading( "idm_saving" );
                    psAlert({
                        "title": "Saved",
                        "message": "Settings were saved."
                    });
                });
            },

            range: function(start, stop) {
                let retArray = []
                for (let i=start; i<=stop; i++) {
                    retArray.push(i)
                }
                return retArray
            },

            flashFill: function(type, index) {
                let startValue = $scope.ctrlData.form[type + "-" + index].value
                let regex = new RegExp(`${index}\\b`, 'g')
                let max = $scope.ctrlData.form[type + "Maximum"].value
                for (let i=index+1; i<=max; i++) {
                    if ($scope.ctrlData.form[type + "-" + i].value) {
                        break;
                    } else {
                        $scope.ctrlData.form[type + "-" + i].value = startValue.replace(regex, i)
                    }
                }
            },
            
            courseResource: {
                getAllCourses: function() {
                    return $http.get('/ws/xte/course');
                },
                getCoursesByYearId: function(yearId) {
                    return $http.get('/ws/xte/course', {
                        params: {
                            year_id: yearId
                        }
                    });
                },
                getCoursesLike: function(parameter) {
                    return $http.get('/ws/xte/course/search', {
                        params: {
                            like: parameter
                        }
                    });
                }
            },

            toggleFieldValue: function(field, value) {
                if (field.value.includes(value)) {
                    field.value = _.without(field.value, value)
                    if (field.value.length == 0) {
                        field.value = ["none"]
                    }
                } else {
                    field.value.push(value)
                    if (field.value.includes("none")) {
                        field.value = _.without(field.value, "none")
                    }
                }
            }
        }
    }]);
});