var CourseNamesView = Backbone.View.extend({
    fullCollection: {},
    formModal: null,
    deletionModal: {},
    editedCollection: {},
    isAdded: false,
    paymentTypeMapping: {},
    hasAccess: false,
    TOTAL_COURSES: 5,

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-course-names-trigger': 'editCourseName',
        'click .save-button': 'saveCourseName',
        // 'click .delete-button': 'deletionModal',
        // 'click #delete-course-name-confirm': 'deleteCourseName',
        // 'click #add-course-name': 'addCourseName'
    },

    breadcrumb: {},

    styles: [
        'ap-blue',
        '#31619e'
    ],

    inventoryStyleMapping: {},

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.courseNamesFormTemplate = options.courseNamesFormTemplate; 
        this.breadcrumb = options.breadcrumb;
        this.collection = options.collection;
        this.listenTo(this.collection, 'reset', this.render);
        this.listenTo(this.collection, 'remove', this.render);
        this.listenTo(this.collection, 'add', this.render);
        this.model = options.model;
        this.initCourseNames();
    },

    render: function () {
        var that = this;
        this.$el.html(this.template({
            courseNames: this.collection.toJSON(),
        }));
        
        var that = this;

        App.breadCrumbToolTip = "Set course names";
        
        $(document).ready(function(){
            $('.tooltipped').tooltip({delay: 0});
            $('.modal').modal();
        });
            
        App.setBreadcrumbs(this.breadcrumb);

        $(document).on('keydown', 'input, select', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
            if (e.keyCode == 13) {
                that.$el.find(".save-button").trigger("click");
                return false;
            }
        });

        $('.tooltipped').tooltip();
        this.formModal = this.$el.find('#course-names-form-modal').modal();
        return this;
    },

    editCourseName: function (e) {
        if (this.hasAccess) {
            var element = $(e.currentTarget);
            var id = $(element).attr('data-id');
            
            if (this.collection.byNumber(id) !== null && this.collection.byNumber(id) !== '') {
                this.courseNamesFormView = new CourseNamesFormView({
                    template: this.courseNamesFormTemplate,
                    model: this.collection.byNumber(id),
                });
    
                this.$el.find('#course-names-form-modal').html(this.courseNamesFormView.render().el);
                this.formModal.modal('open');
            }
            else {
                M.toast({ html: '{Literal}There was a problem fetching data from the server{/Literal}' });
            }
        }
        else {
            M.toast({ html: '{Literal}You do not have access to edit Course Names{/Literal}' });
        }

    },

    addCourseName: function (e) {
        if (this.hasAccess) {
            this.isAdded = true;
            var courseNames = new CourseNames();
            this.courseNamesFormView = new CourseNamesFormView({
                template: this.courseNamesFormTemplate,
                model: courseNames
            });
    
            this.$el.find('#course-names-form-modal').html(this.courseNamesFormView.render().el);
            this.$el.find('select').formSelect();
            this.$el.find("select[required]").css({
                display: "block", 
                position: 'absolute',
                visibility: 'hidden'
            });  
            this.formModal.modal('open');
        }
        else {
            M.toast({ html: '{Literal}You do not have access to edit Course Names{/Literal}' });
        }
    },

    highlightCard: function (e) {
        this.$el.find('.edit').hide();
        this.$el.find('.card-panel-entity').removeClass('active');
        var element = $(e.currentTarget);
        var selected = $(element).attr('data-selected') === '1';
        
        if (selected) {
            $(element).removeAttr('data-selected');
            $(element).removeClass('active');
            $(element).find('.edit').hide();
        } else {
            $(element).removeAttr('data-selected');
            $(element).attr('data-selected', '1');
            $(element).find('.edit').show();
            $(element).addClass('active');
        }
    },

    initCourseNames: function () {
        this.checkAccess();
        this.getCourseNames();
    },

    checkAccess: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_COMPS),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.hasAccess = true;
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.hasAccess = false;
                }
            }
        });
    },
    
    getCookie: function() {
        var nameEQ = "sessionCookie" + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    },

    courseNames: [],

    getCourseNames: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-course-names',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.courseNames = data.results;
                for (var i = 0; i < that.TOTAL_COURSES; i++) {
                    if(that.courseNames[i] == null || that.courseNames[i] == undefined)
                        that.courseNames.push({number: i+1, name: ''}) 
                }
                that.generateCourseNamesStyleMapping(that.courseNames);
                that.renderCourseNames(that.courseNames);  
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching data from the server{/Literal}'
                    });
                }
            }
        });
    },

    renderCourseNames: function (data) {
        var that = this;
        
        data.sort(function (a, b) {
            return a.number < b.number ? -1 : (a.number > b.number ? 1 : 0);
        });
        var collection = new CourseNamesCollection();
        for (var i = 0; i < data.length; i++) {
            var currentCourseName = data[i];
            currentCourseName.cardStyleClass = that.inventoryStyleMapping[data[i].id];
            
            collection.add(new CourseNames(currentCourseName));
        }
        that.fullCollection = collection;
        that.collection.reset(collection.models);
},

    generateCourseNamesStyleMapping: function (data) {
        var inventory = [];
        var totalStyles = this.styles.length;
        var currentStyle = 0;
        for (var i = 0; i < data.length; i++) {
            if (inventory.indexOf(data[i].id) < 0) {
                inventory.push(data[i].id);
                this.inventoryStyleMapping[data[i].id] = this.styles[currentStyle];
                if (currentStyle < totalStyles - 1) {
                    currentStyle++;
                } else {
                    currentStyle = 0;
                }
            }
        }
    },

    getFormValues: function () {
        var number = this.$el.find('#id').val();
        var courseName = this.$el.find('#courseName').val();
        if (number == "" || number == undefined || number == null) {
            number = this.collection.length
        }
        if (this.isAdded) {
           
            var updatedModel = {
                number: number,
                name: courseName,
                // isAdded: true
            };
            this.isAdded = false;
        }
        else {
            var updatedModel = {
                number: number,
                name: courseName,
                // isAdded: false
            };
        }

        this.editedCollection = new CourseNamesCollection();
        this.courseNamesFormView.model.set(updatedModel);
        this.editedCollection.add(this.courseNamesFormView.model); 
    },

    validateForm: function () {
        var valid = true;

        var validateCourseName = this.$el.find("#courseName").val();
        if (validateCourseName.trim().length < 1) {
            this.$el.find("#qtyReceived").addClass("invalid");
            valid = false;
        }
        else
        {
            iChars = "`~@$%^*()_+=[]{}:;,<>./?*\\\'\"";
            for (var i = 0; i < validateCourseName.length; i++) {
                if (iChars.indexOf(validateCourseName.charAt(i)) != -1) {
                    this.$el.find("#courseName").addClass("invalid");
                    valid = false;
                    break;
                }
            }
        }

        return valid;
    },

    deletionModal: function (e) {
        var that = this;
        var element = $(e.currentTarget);
        var courseNameId = $(element).attr('data-id');
        $("#delete-course-name-id").val(courseNameId);
        $('#delete-course-name-modal').modal().modal('open');
    },

    deleteCourseName: function(e) {
        var that = this;
        var element = $(e.currentTarget);
        var courseNameId = $(element).attr("data-course-name-id");
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/delete-course-names',
            data: {
                id: (that.courseNamesFormView.model.attributes.id),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.collection.remove(courseNameId);
                M.toast({ html: '{Literal}Course Name removed successfully{/Literal}' });
                        
                that.render();
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem removing this Course Name item{/Literal}' });
                }
            }
        });
    },

    saveCourseName: function (){
        if (this.hasAccess) {
            var that = this;
            var validation = this.validateForm();
            var updateCollection = that.collection;
            if (validation) {
                this.getFormValues();
                var that = this;
                var updateCollection = that.collection;
                var sessionToken = this.getCookie();
                // var courseName = {
                //     id: that.courseNamesFormView.model.attributes.id,
                //     name: that.courseNamesFormView.model.attributes.courseName,
                // }
                // if(that.courseNamesFormView.model.attributes.isAdded)
                //     courseName.id = 0;
                var courseNames = this.collection.toJSON();

                $.ajax({
                    url: '/data/save-course-names',
                    data: {
                        courseNames: JSON.stringify(courseNames),
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',
    
                    success: function (data) {
                        if (data.success) {
                            newModel = (that.courseNamesFormView.model);
                            updateCollection.add(newModel);
                            M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
                            that.initCourseNames();
                            that.render();
                        }
    
                    },
    
                    error: function (e) {
                        if (e.status == 523) {
                            window.location.href = "#/log-in";
                            location.reload();
                        }
                        else {
                            M.toast({ html: '{Literal}There was a problem saving this Course Name item{/Literal}' });
                        }
                    }
                });
            }
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Add/Edit Course Names{/Literal}' });
        }
    }
});