var RemotePrintingView = Backbone.View.extend({
    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .pagination-trigger': 'handlePageClickEvent',
        'click #pagination-back': 'handlePageBackEvent',
        'click #pagination-forward': 'handlePageForwardEvent',
        'click .edit-items-trigger': 'editItems',
        'click #add-items-button': 'addItems',
        'click .save-button': 'saveRemotePrintSettings',
        'click #editAppetizers' : 'openAppetizerModal',
        'click .appetizerCard' : 'chooseAppetizer',
        'click #editRemotePrintingSettings' : 'editRemotePrintingSettings',
        'click .save-remote-printing-button': 'saveRemotePrintingInfo',
        'click #addItemType': 'addItemType',
        'click .edit-printer-trigger': 'editRemotePrinter',
    },

    breadcrumb: {},

    itemsStyleMapping: {},

    styles: [
        'ap-blue',
    ],

    printerArray: [],

    appetizers: [],

    remotePrintingInfo: {},

    userGroups: [],

    printerNames: [],

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.remotePrintingFormTemplate = options.remotePrintingFormTemplate;
        this.breadcrumb = options.breadcrumb;
        this.model = options.model;
        this.initItemTypes();
    },

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

    render: function () {
        App.breadCrumbToolTip = "Choose what items will be printed to a remote printer"

        App.setBreadcrumbs(this.breadcrumb);

        this.deletionModal = $(".modal").modal();
        var that = this;
        $(document).ready(function(){
            $('.modal').modal();
            $('select').formSelect();
            $('.fixed-action-btn').floatingActionButton();
        });
        $('.tooltipped').tooltip();
        this.formModal = this.$el.find('#remote-printing-form-modal').modal();
        
        $(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;
            }
        });

        return this;
    },
    
    initItemTypes:  function () {
        this.getItemTypes();
    },

    getItemTypes: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-item-types',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                data.results.sort(function (a, b) {
                    return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0);
                });
                that.itemTypes = data.results;
                that.renderItemTypes(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}' });
                }
            }
        });
    },

    renderItemTypes: function (data) {
        var that = this;
        var currentItemTypes = [];
        for (var i = 0; i < data.length; i++) {
            currentItemTypes.push(data[i]);   
        }
        
        this.initRemotePrinting();
    },

    initRemotePrinting: function() {
        this.getRemotePrinting();
    },

    getRemotePrinting: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-remote-printing-info',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.appetizers = data.appetizers;
                that.printerNames = data.printerNames;
                that.remotePrintingInfo = {
                    decimals: data.decimals,
                    printSKU: data.printSKU,
                    textOrientation: data.textOrientation
                }
                that.userGroups = data.userGroups;
                that.renderRemotePrinting(data);
            },
            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}' });
                }
            }
        });
    },

    renderRemotePrinting: function(data) {
        var that = this;
        this.generateRemotePrintingStyleMapping(data);

        data.printList.sort(function (a, b) {
            return a.itemType < b.itemType ? -1 : (a.itemType > b.itemType ? 1 : 0);
        });
        
        that.printerArray = [];

        for (var i = 0; i < data.printList.length; i++) {
            var currentItems = data.printList[i];
            currentItems.id = i;
            that.printerArray.push(currentItems);
        }
        
        this.$el.html(this.template({
            itemTypes: this.itemTypes,
            printerArray: this.printerArray,
            appetizers: this.appetizers,
            remotePrintingInfo: this.remotePrintingInfo,
            userGroups: this.userGroups
        }));

        $('.modal').modal();
        $('select').formSelect();
        $('.fixed-action-btn').floatingActionButton();
        $('.tooltipped').tooltip();
    },

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

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

    openAppetizerModal: function() {
        var apptizerFormModal = this.$el.find('#appetizer-form-modal').modal();
        apptizerFormModal.modal('open');
    },

    chooseAppetizer: function(e) {
        var element = $(e.currentTarget);
        var id = $(element).attr('data-id');
        if ($(element).css('background-color') == "rgb(57, 112, 183)") {
            $(element).css('background-color', '#ffffff')
            $(element).attr('style', 'color: #3970b7 !important;');
        }
        else if ($(element).css('background-color') == "rgb(255, 255, 255)") {
            $(element).css('background-color', '#3970b7')
            $(element).css('color', '#ffffff')
        }
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/set-appetizers',
            data: {
                token: sessionToken,
                appetizer: id
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                M.toast({ html: '{Literal}Appetizer changed successfully{/Literal}' });
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem saving your appetizer settings{/Literal}' });
                }
            }
        });
    },

    editRemotePrintingSettings: function() {
        var remotePrintingFormModal = this.$el.find('#remote-printing-form-modal').modal();
        remotePrintingFormModal.modal('open');
    },

    saveRemotePrintingInfo: function() {
        var that = this;
        var sessionToken = this.getCookie();
        var decimals = this.$el.find('#decimals').val();
        var printSKU = this.$el.find('#printSKU:checked').length > 0;
        var textOrientation = this.$el.find('#textOrientation:checked').length > 0;

        $.ajax({
            url: '/data/edit-remote-printing-info',
            data: {
                token: sessionToken,
                decimals: decimals,
                printSKU: printSKU,
                textOrientation: textOrientation
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem saving your settings{/Literal}' });
                }
            }
        });
    },
    
    addItemType: function() {
        var remotePrinting = new RemotePrinting();
        this.remotePrintingFormView = new RemotePrintingFormView({
            template: this.remotePrintingFormTemplate,
            model: remotePrinting,
            itemTypes: this.itemTypes,
            userGroups: this.userGroups,
            printerNames: this.printerNames
        });

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

    saveRemotePrintSettings: function() {
        var that = this;
        var sessionToken = this.getCookie();

        var isAdded = false;

        var itemType = this.remotePrintingFormView.$el.find('#item-type-dropdown option:selected').text();
        var printer = this.remotePrintingFormView.$el.find('#printer-dropdown option:selected').text();
        var font = this.remotePrintingFormView.$el.find('#font-dropdown option:selected').text();
        var fontSize = this.remotePrintingFormView.$el.find('#font-size-dropdown option:selected').text();
        var userGroup = this.remotePrintingFormView.$el.find('#user-group-dropdown option:selected').text();

        var printerValue = this.remotePrintingFormView.$el.find('#printer-dropdown').val();
        var itemTypeValue = this.remotePrintingFormView.$el.find('#item-type-dropdown').val();

        var id = this.$el.find('#id').val();

        if (itemTypeValue == "choose" || printerValue == "choose") {
            M.toast({ html: '{Literal}An item type and a printer are required{/Literal}' });
        }
        else {
            var updatedModel = {
                itemType: itemType,
                printer: printer,
                font: font,
                fontSize: fontSize,
                userGroup: userGroup,
                id: id
            }

            if (id == '') {
                isAdded == true;
            }
            $.ajax({
                url: '/data/save-remote-printer',
                data: {
                    token: sessionToken,
                    itemType: itemType,
                    printer: printer,
                    font: font,
                    fontSize: fontSize,
                    userGroup: userGroup,
                    printSKU: that.remotePrintingInfo.printSKU, 
                    decimals: that.remotePrintingInfo.decimals, 
                    textOrientation: that.remotePrintingInfo.textOrientation, 
                    isAdded: isAdded
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });

                    that.printerArray.push(updatedModel);
                    that.formModal = that.$el.find('#remote-printing-form-modal').modal();
                    that.formModal.modal('close');
                    that.initItemTypes();
                    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 your settings{/Literal}' });
                    }
                }
            });
        }
    },

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

        for (var i = 0; i < this.printerArray.length; i++) {
            if (this.printerArray[i].id == id) {
                this.remotePrintingFormView = new RemotePrintingFormView({
                    template: this.remotePrintingFormTemplate,
                    model: this.printerArray[i],
                    itemTypes: this.itemTypes,
                    userGroups: this.userGroups,
                    printerNames: this.printerNames
                });
                this.$el.find('#remote-printing-form-modal').html(this.remotePrintingFormView.render().el);
                this.$el.find('select').formSelect();
                this.$el.find("select[required]").css({
                    display: "block", 
                    position: 'absolute',
                    visibility: 'hidden'
                });  
                this.formModal = this.$el.find('#remote-printing-form-modal').modal();
                this.formModal.modal('open');

                break;
            }
        }
    }
});