var TriPOSView = Backbone.View.extend({
    fullCollection: {},
    deletionModal: {},
    formModal: null,
    deleteId: "",
    companyInfo: {},

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-tripos-trigger': 'editTriPOS',
        'click #add-tripos': 'addTriPOS',
        'click .delete-button' : 'deletionModal',
        'click .save-button': 'saveTriPOS',
        'click #delete-tripos-confirm': 'deleteTriPOS',
        'click #additional-setup-confirm-btn': 'modifyTriPOSTerminal',
        'click .modify-button' : 'showAdditionalSetupModal'
    },

    breadcrumb: {},

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

    triPOSStyleMapping: {},

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

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

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

        App.breadCrumbToolTip = "Set up or edit your triPOS Terminals";
            
        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) {
                focusable = form.find('input,a,select,button,select').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    form.submit();
                }
                return false;
            }
        });

        this.formModal = this.$el.find('#tripos-form-modal').modal();
        return this;
    },

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

    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);
        }
    },
    
    getTriPOS: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-tri-pos-terminals',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.companyInfo = data.results[data.results.length - 1]
                that.generateTriPOSStyleMapping(data.results);
                that.renderTriPOS(data.results);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem fetching item types from the server{/Literal}' });
                }
            }
        });
    },

    renderTriPOS: function (data) {
        var that = this;
        data.sort(function (a, b) {
            return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
        });
        var collection = new TriPOSCollection();
        for (var i = 0; i < data.length ; i++) {
            var currentTerminal = data[i];
            currentTerminal.cardStyleClass = that.triPOSStyleMapping[data[i].id];
            
            collection.add(new TriPOS(currentTerminal));
        }
        that.fullCollection = collection;
        that.collection.reset(collection.models);
    },

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

    editTriPOS: function (e) {
        var element = $(e.currentTarget);
        var id = $(element).attr('data-id');

        if (this.collection.get(id) !== null && this.collection.get(id) !== '') {
            document.getElementById('additional-setup-modal').dataset.terminalid = this.collection.get(id).attributes.terminalId;
            this.triPOSFormView = new TriPOSFormView({
                template: this.triPOSFormTemplate,
                model: this.collection.get(id),
            });

            this.$el.find('#tripos-form-modal').html(this.triPOSFormView.render().el);
            this.formModal.modal('open');
        }
        else {
            M.toast({ html: '{Literal}There was a problem fetching data from the server{/Literal}' });
        }
    },

    addTriPOS: function (e) {
        this.isAdded = true;
        var triPOS = new TriPOS();
        // triPOS.attributes.address1 = this.companyInfo.address1
        // triPOS.attributes.address2 = this.companyInfo.address2
        // triPOS.attributes.city = this.companyInfo.city
        // triPOS.attributes.name = this.companyInfo.name
        // triPOS.attributes.phone = this.companyInfo.phone
        // triPOS.attributes.state = this.companyInfo.state
        // triPOS.attributes.zip = this.companyInfo.zip

        this.triPOSFormView = new TriPOSFormView({
            template: this.triPOSFormTemplate,
            model: triPOS
        });

        this.$el.find('#tripos-form-modal').html(this.triPOSFormView.render().el);
        this.$el.find('select').formSelect();
        this.$el.find("select[required]").css({
            display: "block", 
            position: 'absolute',
            visibility: 'hidden'
        });  
        this.formModal.modal('open');
    },

    validateForm: function () {
        var valid = true;

        var validateTerminalId = this.$el.find("#terminalId").val();
       
        var validateDescription = this.$el.find("#description").val();
        var activationCode = this.$el.find("#activationCode").val();
        var iChars = "`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
        var numberChars = "0123456789`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
        var letterChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*_+=[]{}:;,<>./?*\\\'\"";


        if (validateDescription.trim().length < 1) {
            this.$el.find("#description").addClass("invalid");
            valid = false;
        }

        if (activationCode.trim().length < 1) {
            this.$el.find("#activationCode").addClass("invalid");
            valid = false;
        }

        // if (validateTerminalId == '') {

        //     var validateName = this.$el.find("#companyName").val();
        //     var validateAddress1 = this.$el.find("#address1").val();
        //     var validateCity = this.$el.find("#city").val();
        //     var validateState = this.$el.find("#state").val();
        //     var validateZip = this.$el.find("#zip").val();
        //     var validateEmail = this.$el.find("#email").val();
        //     var validatePhone = this.$el.find("#phone").val();
        //     var validateContactName = this.$el.find('#contactName').val();
            
        //     if (validateName.trim().length < 1) {
        //         this.$el.find("#companyName").addClass("invalid");
        //         valid = false;
        //     }

        //     if (validateAddress1.trim().length < 1) {
        //         this.$el.find("#address1").addClass("invalid");
        //         valid = false;
        //     }
        //     else {
        //         for (var i = 0; i < validateAddress1.length; i++) {
        //             if (iChars.indexOf(validateAddress1.charAt(i)) != -1) {
        //                 this.$el.find("#address1").addClass("invalid");
        //                 valid = false;
        //                 break;
        //             }
        //         }
        //     }

        //     if (validateCity.trim().length < 1) {
        //         this.$el.find("#city").addClass("invalid");
        //         valid = false;
        //     }
        //     else {
        //         for (var i = 0; i < validateCity.length; i++) {
        //             if (iChars.indexOf(validateCity.charAt(i)) != -1) {
        //                 this.$el.find("#city").addClass("invalid");
        //                 valid = false;
        //                 break;
        //             }
        //         }
        //     }
            
        //     if (validateContactName.trim().length < 1) {
        //         this.$el.find("#contactName").addClass("invalid");
        //         valid = false;
        //     }
        //     else {
        //         for (var i = 0; i < validateContactName.length; i++) {
        //             if (iChars.indexOf(validateContactName.charAt(i)) != -1) {
        //                 this.$el.find("#contactName").addClass("invalid");
        //                 valid = false;
        //                 break;
        //             }
        //         }
        //     }

        //     if (validateState.trim().length < 1) {
        //         this.$el.find("#state").addClass("invalid");
        //         valid = false;
        //     }
        //     for (var i = 0; i < validateState.length; i++) {
        //         if (numberChars.indexOf(validateState.charAt(i)) != -1) {
        //             this.$el.find("#state").addClass("invalid");
        //             valid = false;
        //             break;
        //         }
        //     }

        //     if (validateZip.trim().length < 1) {
        //         this.$el.find("#zip").addClass("invalid");
        //         valid = false;
        //     }
        //     else if (validateZip.indexOf("-") > -1 || validateZip.indexOf('e') > -1) {
        //         this.$el.find("#zip").addClass("invalid");
        //         valid = false;
        //     }

        //     if (validateEmail.trim().length < 1) {
        //         this.$el.find("#email").addClass("invalid");
        //         valid = false;
        //     }

        //     if (validatePhone.trim().length < 1) {
        //         this.$el.find("#phone").addClass("invalid");
        //         valid = false;
        //     }
        //     else {
        //         for (var i = 0; i < validatePhone.length; i++) {
        //             if (letterChars.indexOf(validatePhone.charAt(i)) != -1) {
        //                 this.$el.find("#telephone").addClass("invalid");
        //                 valid = false;
        //                 break;
        //             }
        //         }
        //     }
        // }

        return valid;
    },

    deletionModal: function () {
        $('#delete-tripos-modal').modal().modal('open');
    },

    saveTriPOS: function () {
        var that = this;
        var validation = this.validateForm();
        var sessionToken = this.getCookie();
        var updateCollection = that.collection;
        that.showSpinner();

        if (validation) {
            that.showSpinner();
            var terminalId = this.$el.find("#terminalId").val();
            var description = this.$el.find("#description").val();
            var activationCode = this.$el.find("#activationCode").val();
            // if (terminalId == '') {
                // var name = this.$el.find('#companyName').val();
                // var email = this.$el.find('#email').val();
                // var address1 = this.$el.find('#address1').val();
                // var city = this.$el.find('#city').val();
                // var state = this.$el.find('#state').val();
                // var phone = this.$el.find('#phone').val();
                // var zip = this.$el.find('#zip').val();
                // var contactName = this.$el.find('#contactName').val();

                $.ajax({
                    url: '/data/add-tripos-terminal',
                    data: {
                        description: description,
                        activationCode: activationCode,
                        terminalId: terminalId,
                        // name: name,
                        // email: email,
                        // address1: address1,
                        // city: city,
                        // state: state,
                        // phone: phone,
                        // zip: zip,
                        // contactName: contactName,
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',
        
                    success: function (data) {
                        that.$el.find(".save-button").addClass("disabled");

                        if(data.success) {
                                if(that.collection.length == 0) {   
                                    that.showAdditionalSetupModal();
                                    document.getElementById('additional-setup-modal').dataset.terminalid = terminalId;
                                }
                                that.collection.add( {id: serialNumber, description: description, terminalId: terminalId})
                                that.formModal.modal('close');
                                App.showToast('{Literal}Settings saved successfully{/Literal}');
                            }
                        else
                            App.showToast('{Literal}There was a problem saving tripos settings{/Literal}');
                    },
                    error: function (e) {
                        if (e.status == 523) {
                            window.location.href = "#/log-in";
                            location.reload();
                        }
                        else if (e.status == 533) {
                            App.showToast('{Literal}The terminal has not been registered yet{/Literal}');
                        }
                        else {
                            App.showToast('{Literal}There was a problem saving tripos settings{/Literal}');
                        }
                    },
                    complete: function () {
                        that.hideSpinner();
                    }
                });
            // }
            // else {
            //     $.ajax({
            //         url: '/data/edit-tripos-terminal',
            //         data: {
            //             terminalName: terminalName,
            //             terminalId: terminalId,
            //             token: sessionToken
            //         },
            //         dataType: 'json',
            //         type: 'POST',
        
            //         success: function (data) {
            //             that.triPOSFormView.model.attributes.terminalName = terminalName;

            //             updateCollection.add(that.triPOSFormView.model);
            //             M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
            //             that.render();
            //         },
        
            //         error: function (e) {
            //             if (e.status == 523) {
            //                 window.location.href = "#/log-in";
            //                 location.reload();
            //             }
            //             else {
            //                 App.showToast('{Literal}There was a problem saving receipt settings{/Literal}');
            //             }
            //         },
            //         complete: function () {
            //             this.$el.find(".save-button").removeClass("disabled");
            //         }
            //     });
            // }
        }
        else {
            App.showToast('{Literal}Some of the required fields are missing or invalid{/Literal}');
        }
    },

    deleteTriPOS: function(e) {
        $('#delete-tripos-modal').modal().modal('close');
        var that = this;
        var element = $(e.currentTarget);
        var terminalId = $(element).attr("data-tripos-terminalId");
        var id = $(element).attr("data-tripos-id");
        var sessionToken = this.getCookie();
        that.showSpinner();

        $.ajax({
            url: '/data/remove-tripos-terminal',
            data: {
                terminalId: terminalId,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                if(data.success)
                that.collection.remove(id);
                M.toast({ html: '{Literal}triPOS Terminal removed successfully{/Literal}' });
                that.render();
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.status == 533) {
                    App.showToast('{Literal}The terminal has not been removed yet{/Literal}');
                }
                else {
                    M.toast({ html: '{Literal}There was a problem removing this triPOS Terminal{/Literal}' });
                }
            },
            complete: function() {
                that.hideSpinner();
                $('#tripos-form-modal').modal().modal('close');
            }
        });
    },

    showSpinner: function() {
        this.$el.find('.signature-modal-trigger-preloader').addClass('active');
        this.$el.find('#spinner').show();
    },

    hideSpinner: function() {
        this.$el.find('.signature-modal-trigger-preloader').removeClass('active');
        this.$el.find('#spinner').hide();
    },

    showAdditionalSetupModal: function() {
        $('#additional-setup-modal').modal().modal('open');
    },

    modifyTriPOSTerminal: function(e) {
        
        var that = this;
        var terminalId = document.getElementById('additional-setup-modal').dataset.terminalid;
        var sessionToken = this.getCookie();
        that.showSpinner();

        $.ajax({
            url: '/data/modify-tripos-terminal',
            data: {
                terminalId: terminalId,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                if(data.success)
                that.collection.remove(id);
                M.toast({ html: '{Literal}triPOS Terminal updated 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 updating this triPOS Terminal{/Literal}' });
                }
            },
            complete: function() {
                that.hideSpinner();
            }
        });
    },

});