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

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-item-attributes-trigger': 'editItemAttributes',
        'click .save-button': 'saveItemAttributes',
        // 'click #add-item-attributes': 'addItemAttributes',
    },

    breadcrumb: {},

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

    inventoryStyleMapping: {},

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

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

        var that = this;

        App.breadCrumbToolTip = "Set Item Attributes";

        $(document).ready(function () {
            $('.tooltipped').tooltip({ delay: 0 });
            $('.modal').modal();
            var elems = document.querySelectorAll('.fixed-action-btn');
            var instances = M.FloatingActionButton.init(elems, {});
        });

        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('#item-attributes-form-modal').modal();
        return this;
    },

    editItemAttributes: function (e) {
        if (this.hasAccess) {
            var element = $(e.currentTarget);
            var attributeNumber = $(element).attr('data-id');

            if (this.collection.get(attributeNumber) !== null && this.collection.get(attributeNumber) !== '') {
                this.itemAttributesFormView = new ItemAttributesFormView({
                    template: this.itemAttributesFormTemplate,
                    model: this.collection.get(attributeNumber),
                    isNew: false
                });

                this.$el.find('#item-attributes-form-modal').html(this.itemAttributesFormView.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 Item Attributes{/Literal}' });
        }

    },

    addItemAttributes: function () {
        if (this.hasAccess) {
            this.isAdded = true;
            var itemAttributes = new ItemAttributes();
            itemAttributes.attributes.attributes = [{ code: '', description: '' }];
            this.itemAttributesFormView = new ItemAttributesFormView({
                template: this.itemAttributesFormTemplate,
                model: itemAttributes,
                isNew: true
            });

            this.$el.find('#item-attributes-form-modal').html(this.itemAttributesFormView.render().el);
            this.formModal.modal('open');
        }
        else {
            M.toast({ html: '{Literal}You do not have access to edit Item Attributes{/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');
        }
    },

    initItemAttributes: function () {
        // this.checkAccess();
        this.getItemAttributes();
    },

    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);
        }
    },

    itemAttributes: [],

    getItemAttributes: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-item-attributes',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.itemAttributes = data;
                // that.generateItemAttributesStyleMapping(that.itemAttributes);
                that.renderItemAttributes(that.itemAttributes);
            },
            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}'
                    });
                }
            }
        });
    },

    renderItemAttributes: function (data) {
        var that = this;

        // data.sort(function (a, b) {
        //     return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0);
        // });
        var collection = new ItemAttributesCollection();
        for (var i = 1; i <= 3; i++) {
            var currentItemAttributes = {};
            if(data[i] != undefined) {
                // currentItemAttributes.cardStyleClass = that.inventoryStyleMapping[i];
                currentItemAttributes.id = i;
                currentItemAttributes.attributes = data[i];
                
                collection.add(new ItemAttributes(currentItemAttributes));
            }
            else {
                collection.add(new ItemAttributes({id: i, attributes:[]}));
            }
        }
        that.fullCollection = collection;
        that.collection.reset(collection.models);
    },

    generateItemAttributesStyleMapping: function (data) {
        var inventory = [];
        var totalStyles = this.styles.length;
        var currentStyle = 0;
        for (var i = 1; i < 10; i++) {
            if(data[i] != undefined) {

                if (inventory.indexOf(data[i].attributeNumber) < 0) {
                    inventory.push(data[i].attributeNumber);
                    this.inventoryStyleMapping[data[i].attributeNumber] = this.styles[currentStyle];
                    if (currentStyle < totalStyles - 1) {
                        currentStyle++;
                    } else {
                        currentStyle = 0;
                    }
                }
            }
        }
    },

    getFormValues: function () {

        const attributeNumber = this.$el.find("#attributeNumber").val();

        var attributes = [];
        var attributesTableRows = document.querySelectorAll('.attributes-table tbody tr');
        for (const row of attributesTableRows) {
            const skuComponent = row.querySelector('input[name="skuComponent"]').value;
            const descriptionComponent = row.querySelector('input[name="descriptionComponent"]').value;
            const deleted = row.classList.contains('hide');
            var thisAttributeNumber = attributeNumber;
            if(deleted)
                thisAttributeNumber = 0;
            attributes.push({ attributeNumber:thisAttributeNumber, skuComponent: skuComponent, descriptionComponent: descriptionComponent });
        }
        var updatedModel = {
            attributeNumber: attributeNumber,
            attributes: attributes,
            isAdded: this.isAdded
        };

        this.editedCollection = new ItemAttributesCollection();
        this.itemAttributesFormView.model.set(updatedModel);
        this.editedCollection.add(this.itemAttributesFormView.model);
    },

    validateForm: function () {
        var valid = true;
        const iChars = "`~@$%^*()_+=[]{}:;,<>./?*\\\'\"";
        var attributeNumber = this.$el.find("#attributeNumber").val();

        var otherSKUs = Object.values(this.itemAttributes).flat().filter(i => i.attributeNumber != attributeNumber).map( i => i.skuComponent);
        var thisFormSKUs = [];
        document.querySelectorAll('.attributes-table tbody tr input[name="skuComponent"]').forEach( el => thisFormSKUs.push(el.value));
        var currentStateSKUs = [...thisFormSKUs, ...otherSKUs]


        var attributesTableRows = document.querySelectorAll('.attributes-table tbody tr');
        for (const row of attributesTableRows) {
            const skuComponent = row.querySelector('input[name="skuComponent"]');
            const descriptionComponent = row.querySelector('input[name="descriptionComponent"]');
            if (skuComponent.value.trim().length == '') {
                skuComponent.classList.add('invalid');
                valid = false;
            }
            if (descriptionComponent.value.trim().length == 0) {
                descriptionComponent.classList.add('invalid');
                valid = false;
            }
            for (let i = 0; i < skuComponent.value.length; i++) {
                if (iChars.indexOf(skuComponent.value.charAt(i)) != -1) {
                    skuComponent.classList.add('invalid');
                    valid = false;
                }
            }
            for (let i = 0; i < descriptionComponent.value.length; i++) {
                if (iChars.indexOf(descriptionComponent.value.charAt(i)) != -1) {
                    descriptionComponent.classList.add('invalid');
                    valid = false;
                }
            }


            if(currentStateSKUs.filter( x => x ==skuComponent.value.trim()).length >  1 ){
                valid = false;
                skuComponent.classList.add('invalid');
            }
        }


        return valid;
    },

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

    deleteItemAttributes: function (e) {
        var that = this;
        var attributesName = e.currentTarget.dataset.itemAttributesId;

        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/delete-item-attributes',
            data: {
                id: attributesName,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.collection.remove(that.collection.byName(attributesName));
                M.toast({ html: '{Literal}Item Attributes 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 Item Attributes item{/Literal}' });
                }
            }
        });
    },

    saveItemAttributes: 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 attributeNumber = document.getElementById("attributeNumber").value;
                var itemAttributes = {
                    attributeNumber: attributeNumber,
                    attributes: that.itemAttributesFormView.model.attributes.attributes,
                }
                if (that.itemAttributesFormView.model.attributes.isAdded)
                    itemAttributes.id = 0;

                $.ajax({
                    url: '/data/save-item-attributes',
                    data: {
                        itemAttributes: JSON.stringify(itemAttributes),
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',

                    success: function (data) {
                        if (data.success) {
                            newModel = (that.itemAttributesFormView.model);
                            updateCollection.add(newModel);
                            M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
                            that.formModal.modal('close');
                            that.initItemAttributes();
                            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 Item Attributes item{/Literal}' });
                        }
                    }
                });
            }
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Add/Edit Item Attributes{/Literal}' });
        }
    },
    addAttribute: function (e = undefined, vat, fieldName) {
        var that = this;

        var tbody = document.querySelector(".attributes-table tbody");
        var length = tbody.querySelectorAll('tr').length;
        tbody.insertAdjacentHTML(
            "afterbegin",
      /*html*/ `<tr>
                <td class="input-field"><input name="skuComponent" /><span class="helper-text" data-error="{Literal}This field must be unique and can't be empty or contain special characters{/Literal}"></span></td>
                <td class="input-field"><input name="descriptionComponent"/><span class="helper-text" data-error="{Literal}This field can't be empty or contain special characters{/Literal}"></span></td>
                <td><a class="btn-floating btn-small waves-effect waves-light red" onclick="App.itemAttributesView.removeAttribute(this)">
                <i class="material-icons">remove</i></a>
                </td></tr>`
        );
    },

    removeAttribute: function (el) {
        el.parentElement.parentElement.classList.add('hide');

    },
   
});