var DiscountReasonsView = Backbone.View.extend({
    fullCollection: {},
    formModal: null,
    deletionModal: {},
    editedCollecton: {},
    isAdded: false,
    paymentTypeMapping: {},
    hasAccess: false,

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-discount-reasons-trigger': 'editDiscountReason',
        'click .save-button': 'saveDiscountReason',
        'click .delete-button': 'deletionModal',
        'click #delete-discount-reason-confirm': 'deleteDiscountReason',
        'click #add-discount-reason': 'addDiscountReason'
    },

    breadcrumb: {},

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

    inventoryStyleMapping: {},

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.discountReasonsFormTemplate = options.discountReasonsFormTemplate; 
        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.initDiscountReasons();
    },

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

        App.breadCrumbToolTip = "Set reasons to discount an order";
        
        $(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('#discount-reasons-form-modal').modal();
        return this;
    },

    editDiscountReason: function (e) {
        if (this.hasAccess) {
            var element = $(e.currentTarget);
            var id = $(element).attr('data-id');
            
            if (this.collection.get(id) !== null && this.collection.get(id) !== '') {
                this.discountReasonsFormView = new DiscountReasonsFormView({
                    template: this.discountReasonsFormTemplate,
                    model: this.collection.get(id),
                });
    
                this.$el.find('#discount-reasons-form-modal').html(this.discountReasonsFormView.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 Discount Reasons{/Literal}' });
        }

    },

    addDiscountReason: function (e) {
        if (this.hasAccess) {
            this.isAdded = true;
            var discountReasons = new DiscountReasons();
            this.discountReasonsFormView = new DiscountReasonsFormView({
                template: this.discountReasonsFormTemplate,
                model: discountReasons
            });
    
            this.$el.find('#discount-reasons-form-modal').html(this.discountReasonsFormView.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 Discount Reasons{/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');
        }
    },

    initDiscountReasons: function () {
        this.checkAccess();
        this.getDiscountReasons();
    },

    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) {
                console.log("hello");
                that.hasAccess = true;
            },

            error: function (e) {
                console.log("hello2");
                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);
        }
    },

    discountReasons: [],

    getDiscountReasons: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-discount-reasons',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.discountReasons = data.results;
                // for (var i = 0; i < data.results.length; i++) {
                //     that.discountReasons.push({id: i, discountReason: data.results[i], originalDiscountReason: data.results[i]}) 
                // }
                that.generateDiscountReasonsStyleMapping(that.discountReasons);
                that.renderDiscountReasons(that.discountReasons);  
            },
            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}'
                    });
                }
            }
        });
    },

    renderDiscountReasons: function (data) {
        var that = this;
        
        data.sort(function (a, b) {
            return a.reason.toLowerCase() < b.reason.toLowerCase() ? -1 : (a.reason.toLowerCase() > b.reason.toLowerCase() ? 1 : 0);
        });
        var collection = new DiscountReasonsCollection();
        for (var i = 0; i < data.length; i++) {
            var currentDiscountReason = data[i];
            currentDiscountReason.cardStyleClass = that.inventoryStyleMapping[data[i].id];
            
            collection.add(new DiscountReasons(currentDiscountReason));
        }
        that.fullCollection = collection;
        that.collection.reset(collection.models);
    },

    generateDiscountReasonsStyleMapping: 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 id = this.$el.find('#id').val();
        var discountReason = this.$el.find('#discountReason').val();
        if (id == "" || id == undefined || id == null) {
            id = this.collection.length
        }
        if (this.isAdded) {
           
            var updatedModel = {
                id: id,
                discountReason: discountReason,
                isAdded: true
            };
            this.isAdded = false;
        }
        else {
            var updatedModel = {
                id: id,
                discountReason: discountReason,
                isAdded: false
            };
        }

        this.editedCollecton = new DiscountReasonsCollection();
        this.discountReasonsFormView.model.set(updatedModel);
        this.editedCollecton.add(this.discountReasonsFormView.model); 
    },

    validateForm: function () {
        var valid = true;

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

        return valid;
    },

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

    deleteDiscountReason: function(e) {
        var that = this;
        var element = $(e.currentTarget);
        var discountReasonId = $(element).attr("data-discount-reason-id");
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/delete-discount-reasons',
            data: {
                id: (that.discountReasonsFormView.model.attributes.id),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.collection.remove(discountReasonId);
                M.toast({ html: '{Literal}Discount Reason 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 discount reason item{/Literal}' });
                }
            }
        });
    },

    saveDiscountReason: 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 discountReason = {
                    id: that.discountReasonsFormView.model.attributes.id,
                    reason: that.discountReasonsFormView.model.attributes.discountReason,
                }
                if(that.discountReasonsFormView.model.attributes.isAdded)
                    discountReason.id = 0;

                $.ajax({
                    url: '/data/save-discount-reasons',
                    data: {
                        discountReason: JSON.stringify(discountReason),
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',
    
                    success: function (data) {
                        if (data.success) {
                            newModel = (that.discountReasonsFormView.model);
                            updateCollection.add(newModel);
                            M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
                            that.initDiscountReasons();
                            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 discount reason item{/Literal}' });
                        }
                    }
                });
            }
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Add/Edit Discount Reasons{/Literal}' });
        }
    }
});