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

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-pos-station-trigger': 'editPosStation',
        'click .save-button': 'savePosStation',
    },

    breadcrumb: {},

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

    inventoryStyleMapping: {},

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

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

        var that = this;

        App.breadCrumbToolTip = "Set POS Stations";

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

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

            if (this.collection.get(posStationId) !== null && this.collection.get(posStationId) !== '') {
                this.posStationsFormView = new POSStationsFormView({
                    template: this.posStationsFormTemplate,
                    model: this.collection.get(posStationId),
                    isNew: false
                });

                this.$el.find('#pos-station-form-modal').html(this.posStationsFormView.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 POS Stations{/Literal}' });
        }

    },

    // addItemAttributes: function () {
    //     if (this.hasAccess) {
    //         this.isAdded = true;
    //         var itemAttributes = new ItemAttributes();
    //         itemAttributes.attributes.attributes = [{ code: '', description: '' }];
    //         this.itemAttributesFormView = new PosStationsFormView({
    //             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');
        }
    },

    initPosStations: function () {
        // this.checkAccess();
        this.getPosStations();
    },

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

    posStations: [],

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

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

        var collection = new POSStationsCollection();
        for (var i = 0; i < data.length; i++) {
            
            collection.add(new POSStations(data[i]));
        }
        that.fullCollection = collection;
        that.collection.reset(collection.models);
    },

    getFormValues: function () {

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

       
        var updatedModel = {
            id: posStationId, name: posStationName
        };

        this.editedCollection = new POSStationsCollection();
        this.posStationsFormView.model.set(updatedModel);
        this.editedCollection.add(this.posStationsFormView.model);
        return updatedModel;
    },

    validateForm: function () {
        var valid = true;
        const iChars = "`~@$%^*()_+=[]{}:;,<>./?*\\\'\"";
        var posStationName = document.getElementById("posStationName");
        
        for (let i = 0; i < posStationName.value.length; i++) {
            if (iChars.indexOf(posStationName.value.charAt(i)) != -1) {
                posStationName.classList.add('invalid');
                valid = false;
            }
        }

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

   

    savePosStation: function () {
        if (this.hasAccess) {
            var that = this;
            var validation = this.validateForm();
            var updateCollection = that.collection;
            if (validation) {
                var that = this;
                var updateCollection = that.collection;
                var sessionToken = this.getCookie();
                var posStation = this.getFormValues();
                $.ajax({
                    url: '/data/save-pos-station',
                    data: {
                        posStation: JSON.stringify(posStation),
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',

                    success: function (data) {
                        if (data.success) {
                            newModel = that.posStationsFormView.model;
                            updateCollection.add(newModel);
                            M.toast({ html: '{Literal}POS Station saved successfully{/Literal}' });
                            that.formModal.modal('close');
                            that.initPosStations();
                            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}' });
        }
    },
});