var RemoteDisplayView = Backbone.View.extend({
    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .activeTillCard' : 'openDeleteTill',
        'click #cancel-delete-till' : 'cancelDeleteTill',
        'click .delete-till-confirm' : 'deleteTillConfirm',
        'click .pagination-trigger': 'handlePageClickEvent',
        'click #pagination-back': 'handlePageBackEvent',
        'click #pagination-forward': 'handlePageForwardEvent',
        'click .save-button': 'saveRemoteDeviceSettings',
        'click #editAppetizers' : 'openAppetizerModal',
        'click #settings' : 'openSettingsModal',
        'click .appetizerCard' : 'chooseAppetizer',
        'click #addItemType': 'addItemType',
        'click .edit-device-trigger': 'editRemoteDevice',
        'click .delete-remote-display-button' : 'openDeletionModal',
        'click #delete-remote-device-confirm': 'deleteRemoteDisplayDevice',
        'click .add-item-type' : 'bringUpItemTypes',
        'click .add-till' : 'bringUpTills',
        'click .cancelItemTypeSelect' : 'closeItemTypes',
        'click .cancelTillSelect' : 'closeTills',
        'click .itemTypeCard' : 'chooseItemType',
        'click .tillCard' : 'chooseTill',
        'click .delete-item-type-trigger': 'removeItemType',
        'click .edit-item-type-trigger': 'openEditItemType',
        'click .closeEditItemType1': 'closeEditItemType',
        'click .closeEditItemType2': 'closeEditItemType',
        'click .save-settings' : 'saveSettings'
    },

    breadcrumb: {},
    itemsStyleMapping: {},
    styles: [
        'ap-blue',
    ],
    chosenItemType: "",
    printerArray: [],
    appetizers: [],
    remotePrintingInfo: {},
    userGroups: [],
    printerNames: [],
    tills: [],
    selectedTill: "",
    thisRemoteDevice: {},

    initialize: async function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.remoteDisplayFormTemplate = options.remoteDisplayFormTemplate;
        this.breadcrumb = options.breadcrumb;
        this.model = options.model;
        await this.getRemoteDisplaySettings();
        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}' });
                }
            }
        });
    },

    getTills: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-tills-list',
            data: {
                token: sessionToken,
                includeInactive: false
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                console.log(data)
                data.results.sort(function (a, b) {
                    return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0);
                });
                that.tills = data.results;

                that.renderTills(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}' });
                }
            }
        });
    },

    renderTills: function () 
    {
        this.initRemoteDevices();
    },

    renderItemTypes: function (data) {
        this.getTills();
    },

    initRemoteDevices: function() {
        this.getRemoteDevices();
    },

    getRemoteDevices: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-remote-display-devices',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
         
                that.appetizers = data.appetizers;
                that.remoteDevices = data.remoteDevices;
                that.userGroups = data.userGroups;
                
                that.renderRemoteDevices(data.remoteDevices);
            },
            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}' });
                }
            }
        });
    },
    
    getRemoteDisplaySettings: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-remote-display-settings',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.settings = data.settings;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}{/Literal}' });
                }
            }
        });
    },

    renderRemoteDevices: function(data) {
        var that = this;
        this.generateRemoteDeviceStyleMapping(data);

        that.remoteDevices.sort(function (a, b) {
            return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0);
        });

        for (var i = 0; i < this.remoteDevices.length; i++) {
            this.remoteDevices[i].id = i + 1;
        }


        
        this.$el.html(this.template({
            itemTypes: this.itemTypes,
            tills: this.tills,
            remoteDevices: this.remoteDevices,
            appetizers: this.appetizers,
            userGroups: this.userGroups,
            settings: this.settings
        }));

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

    generateRemoteDeviceStyleMapping: 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;
                }
            }
        }
    },

    openDeleteTill: function(e) {
        var element = $(e.currentTarget);
        var tillId = $(element).attr('data-id');
        this.selectedTill = tillId;
        console.log(tillId);
        var deletionModal = this.$el.find('#delete-till-modal').modal();
        deletionModal.modal('open');
    },

    cancelDeleteTill: function() {
        var deletionModal = this.$el.find('#delete-till-modal').modal();
        deletionModal.modal('close');
    },

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

    openSettingsModal: function() {
        var that = this;
        this.settings.serverConfigModules.forEach( module => {

            that.loadModules(module);
        })
        var settingsFormModal = this.$el.find('#remote-display-settings-form-modal').modal();
        settingsFormModal.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}' });
                }
            }
        });
    },
    
    addItemType: function() {
        var remoteDisplay = new RemoteDisplay();
        this.remoteDisplayFormView = new RemoteDisplayFormView({
            template: this.remoteDisplayFormTemplate,
            model: remoteDisplay,
            tills: this.tills,
            itemTypes: this.itemTypes,
            userGroups: this.userGroups,
        });

        this.$el.find("#remote-display-form-modal").html(this.remoteDisplayFormView.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-display-form-modal').modal();
        this.formModal.modal('open');
    },

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

        var isAdded = false;

        var name = this.remoteDisplayFormView.$el.find('#name').val();
        var address = this.remoteDisplayFormView.$el.find('#address').val();
        var pageWidth = this.remoteDisplayFormView.$el.find('#pageWidth').val();
        var templateName = this.remoteDisplayFormView.$el.find('#templateName').val();
        var deviceType = this.remoteDisplayFormView.$el.find('#device-type-dropdown').val();
        var isMonitor = false;
        var isLabelPrinter = false;
        if (deviceType == 'monitor')
            isMonitor = true;
        else if(deviceType == 'labelPrinter')
            isLabelPrinter = true;
        var userGroup = this.remoteDisplayFormView.$el.find('#user-group-dropdown option:selected').text();

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

        var itemTypeLength = 0;
        var itemTypes = []; 
        for (var i = 0; i < this.remoteDevices.length; i++) {
            if (this.remoteDevices[i].id == id) {
                itemTypeLength = this.remoteDevices[i].itemTypes.length;
                itemTypes = this.remoteDevices[i].itemTypes;
                
            }
        }

        var tillsLength = 0;
        var tills = []; 
        for (var i = 0; i < this.remoteDevices.length; i++) {
            if (this.remoteDevices[i].id == id) {
                tillsLength = this.remoteDevices[i].tills.length;
                tills = this.remoteDevices[i].tills;
            }
        }

        if (name == "" && !this.remoteDisplayFormView.$el.find('#name').prop('disabled')
         || address == "" && !this.remoteDisplayFormView.$el.find('#address').prop('disabled')
         || templateName == "" && !this.remoteDisplayFormView.$el.find('#templateName').prop('disabled')
         || itemTypeLength <= 0) {
            M.toast({ html: '{Literal}Name, Address, Template Name, and at least 1 Item Type is required{/Literal}' });
        }
        else {
            var updatedModel = {
                name: name,
                address: address,
                pageWidth: pageWidth,
                templateName: templateName,
                userGroup: userGroup,
                itemTypes: itemTypes,
                tills: tills,
                isMonitor : isMonitor,
                isLabelPrinter: isLabelPrinter,
                id: id
            }

            if (id == 6666 || id == '') {
                isAdded = true;
            }
            $.ajax({
                url: '/data/save-remote-display-device',
                data: {
                    token: sessionToken,
                    displayDevice: JSON.stringify(updatedModel),
                    isAdded: isAdded
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });

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

    openEditItemType: function(e) {
        $('#itemTypeTillsRow').html("");
        var element = $(e.currentTarget);
        var itemTypeId = $(element).attr('item-type-id');
        var id = $(element).attr('data-id');

        var itemTypeName =  document.getElementById('itemTypeName');
        itemTypeName.value = itemTypeId;

        var matchedRemoteDisplay = null;
        for (var i = 0; i < this.remoteDevices.length; i++) {
            var thisRemoteDisplay = this.remoteDevices[i];
            if (thisRemoteDisplay.id == id) {
                matchedRemoteDisplay = this.remoteDevices[i];
                break;
            }
        }

        var tills = [];
        if (matchedRemoteDisplay != null) {
            tills = matchedRemoteDisplay.tills;
        }

        if (tills.length > 0) {
            for (var i = 0; i < tills.length; i++) {
                var thisTill = tills[i];
                if (thisTill != null && thisTill != "") {
                    var html = "";
                    html += '<div class="col s12 m2 xl2">';
                    html += '<div class="activeTillCard card-panel card-panel-entity z-depth-1 sequence-card hoverable waves-effect waves-light" style="background-color: #ffffff" data-id="' + thisTill + '" data-selected="0"';
                    html += '<div><div id="' + thisTill + '" class="row description truncate" style="color: #3970b7; font-size: 1rem;">' + thisTill + '</div></div>';
                    html += '<div class="tillEdit" style="display: none">';
                    html += '<a href="javascript:void(0)" class="btn-floating btn-large waves-effect waves-light red delete-till-trigger" data-id="' + id + '" item-type-id="' + thisTill + '">';
                    html += '<i class="material-icons">delete</i></a></div></div></div>';
                    $('#itemTypeTillsRow').append(html);
                }
            }
        }

        this.chosenItemType = itemTypeId;

        var editItemTypeModal = this.$el.find('#edit-item-type-modal').modal();
        editItemTypeModal.modal('open');
    },

    editRemoteDevice: function(e) {
        var element = $(e.currentTarget);
        var id = $(element).attr('data-id');
       
        for (var i = 0; i < this.remoteDevices.length; i++) {
            if (this.remoteDevices[i].id == id) {
                var remoteDisplayObject = new RemoteDisplay();
                remoteDisplayObject.attributes = this.remoteDevices[i];
                
                    
                this.remoteDisplayFormView = new RemoteDisplayFormView({
                    template: this.remoteDisplayFormTemplate,
                    model: remoteDisplayObject,
                    itemTypes: this.itemTypes,
                    tills: this.tills,
                    userGroups: this.userGroups,
                });
                this.$el.find("#remote-display-form-modal").html(this.remoteDisplayFormView.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-display-form-modal').modal();
                this.formModal.modal('open');

                break;
            }
        }
    },

    openDeletionModal: function() {
        var deletionModal = this.$el.find('#delete-remote-display-modal').modal();
        deletionModal.modal('open');
    },

    bringUpItemTypes: function() {
        var itemTypeFormModal = this.$el.find('#item-type-form-modal').modal();
        itemTypeFormModal.modal('open');
    },

    bringUpTills: function() {
        var tillsFormModal = this.$el.find('#tills-form-modal').modal();
        tillsFormModal.modal('open');
    },
    
    closeItemTypes: function() {
        var itemTypeFormModal = this.$el.find('#item-type-form-modal').modal();
        itemTypeFormModal.modal('close');
    },

    closeEditItemType: function() {
        var itemTypeFormModal = this.$el.find('#edit-item-type-modal').modal();
        itemTypeFormModal.modal('close');
    },

    closeTills: function() {
        var tillsFormModule = this.$el.find('#tills-form-modal').modal();
        tillsFormModule.modal('close');
    },

    chooseTill: function(e) {
        e.currentTarget.classList.toggle('selected');
        const selected = e.currentTarget.classList.contains('selected');
        var that = this;
        var remoteDeviceId = this.$el.find('#id').val();
        var element = $(e.currentTarget);
        var tillId = $(element).attr('data-id');
        var foundTill = false;

        if (remoteDeviceId == '') {
            var name = this.remoteDisplayFormView.$el.find('#name').val();
            var address = this.remoteDisplayFormView.$el.find('#address').val();
            var pageWidth = this.remoteDisplayFormView.$el.find('#pageWidth').val();
            var templateName = this.remoteDisplayFormView.$el.find('#templateName').val();
            var userGroup = this.remoteDisplayFormView.$el.find('#user-group-dropdown option:selected').text();

            updatedModel = {
                name: name,
                address: address,
                pageWidth: pageWidth,
                templateName: templateName,
                userGroup: userGroup,
                itemTypes: [],
                tills: [],
                id: 6666
            }
            var idValue =  document.getElementById('id');
            idValue.value = "6666"

            var foundBlank = false;
            for (var i = 0; i < this.remoteDevices.length; i++) {
                if (this.remoteDevices[i].id == 6666) {
                    this.remoteDevices[i] = updatedModel;
                    foundBlank = true;
                    break;
                }
            }

            if (!foundBlank) {
                this.remoteDevices.push(updatedModel);
            }

            remoteDeviceId = 6666;
        }


        if (!selected) {
            for (var i = 0; i < this.remoteDevices.length; i++) {
                if (this.remoteDevices[i].id == remoteDeviceId) {
                    this.remoteDevices[i].tills = this.remoteDevices[i].tills.filter( till =>  till != tillId );
                    break;
                }
            }

            document.querySelector('#itemTypeTillsRow .selectedTill').remove();
        }
        else {
            var foundDevice = null;
            for (var i = 0; i < this.remoteDevices.length; i++) {
                var thisRemoteDevice = this.remoteDevices[i];
                if (thisRemoteDevice.id == remoteDeviceId) {
                    foundDevice = thisRemoteDevice;
                    thisRemoteDevice.tills.push(tillId);
                    break;
                }
            }


            var html = `<div class="col s12 m2 xl2 selectedTill">
                            <div class="card-panel card-panel-entity z-depth-1 sequence-card hoverable waves-effect waves-light" style="background-color: #ffffff" data-id="${tillId}" data-selected='0'>
                                <div id="${tillId}" class="row description truncate" style="color: #3970b7; font-size: 1rem;">
                                ${tillId}
                                </div>
                                <div class="edit" style="display: none">
                                    <a href="javascript:void(0)" class="btn-floating btn-large waves-effect waves-light red delete-item-type-trigger"
                                        data-id="${remoteDeviceId}"  item-type-id="${tillId}">
                                        <i class="material-icons">delete</i>
                                    </a>
                                </div>
                            </div>
                        </div>`
            $('#itemTypeTillsRow').append(html);

            for (var j = 0; j < foundDevice.itemTypes.length; j++) {
                var thisItemType = foundDevice.itemTypes[j];
                if (thisItemType.till == undefined) {
                    foundDevice.itemTypes.splice(j, 0);
                }
            }

            for (var i = 0; i < this.remoteDevices.length; i++) {
                var thisRemoteDevice = this.remoteDevices[i];
                if (thisRemoteDevice.id == remoteDeviceId) {
                    this.remoteDevices[i] = foundDevice;
                    break;
                }
            }

            // var tillFormModal = this.$el.find('#tills-form-modal').modal();
            // tillFormModal.modal('close');
        }
    },

    chooseItemType: function(e) {
        e.currentTarget.classList.toggle('selected');
        const selected = e.currentTarget.classList.contains('selected');
        
        var remoteDeviceId = this.$el.find('#id').val();
        var element = $(e.currentTarget);
        var itemTypeId = $(element).attr('data-id');
        var foundItemType = false;
        if (remoteDeviceId == '') {
            
            var name = this.remoteDisplayFormView.$el.find('#name').val();
            var address = this.remoteDisplayFormView.$el.find('#address').val();
            var pageWidth = this.remoteDisplayFormView.$el.find('#pageWidth').val();
            var templateName = this.remoteDisplayFormView.$el.find('#templateName').val();
            var userGroup = this.remoteDisplayFormView.$el.find('#user-group-dropdown option:selected').text();

            updatedModel = {
                name: name,
                address: address,
                pageWidth: pageWidth,
                templateName: templateName,
                userGroup: userGroup,
                itemTypes: [],
                tills:[],
                id: 6666
            }
            var idValue =  document.getElementById('id');
            idValue.value = "6666"

            var foundBlank = false;
            for (var i = 0; i < this.remoteDevices.length; i++) {
                if (this.remoteDevices[i].id == 6666) {
                    this.remoteDevices[i] = updatedModel;
                    foundBlank = true;
                    break;
                }
            }

            if (!foundBlank) {
                this.remoteDevices.push(updatedModel);
            }

            remoteDeviceId = 6666;
        }


        if (!selected) {
            for (var i = 0; i < this.remoteDevices.length; i++) {
                if (this.remoteDevices[i].id == remoteDeviceId) {
                    this.remoteDevices[i].itemTypes = this.remoteDevices[i].itemTypes.filter( thisItemType =>  thisItemType != itemTypeId );
                    break;
                }
            }

            document.querySelector('#itemTypeBlock .selectedItemType').remove();

        }
        else {
            for (var i = 0; i < this.remoteDevices.length; i++) {
                if (this.remoteDevices[i].id == remoteDeviceId) {
                    this.remoteDevices[i].itemTypes.push(itemTypeId);
                    break;
                }
            }
            
            var html = `<div class="col s12 m2 xl2 selectedItemType">
                            <div class="card-panel card-panel-entity z-depth-1 sequence-card hoverable waves-effect waves-light" style="background-color: #ffffff" data-id="${itemTypeId}" data-selected='0'>
                                <div>
                                    <div id="${itemTypeId}" class="row description truncate" style="color: #3970b7; font-size: 1rem;">
                                    ${itemTypeId}
                                    </div>
                                </div>
                                <div class="edit" style="display: none">
                                    <a href="javascript:void(0)" class="btn-floating btn-large waves-effect waves-light red delete-item-type-trigger"
                                        data-id="${remoteDeviceId}"  item-type-id="${itemTypeId}">
                                        <i class="material-icons">delete</i>
                                    </a>
                                </div>
                            </div>
                        </div>`;


            $('#itemTypeBlock').append(html);

            // var itemTypeFormModal = this.$el.find('#item-type-form-modal').modal();
            // itemTypeFormModal.modal('close');
        }
    },

    deleteTillConfirm: function(e) {
        var remoteDisplayId = e.currentTarget.dataset.id;
        var till = e.currentTarget.dataset.till;
        var that = this;
        var sessionToken = this.getCookie();
        // var itemType = this.remoteDisplayFormView.$el.find('#itemTypeName').val();
        // var remoteDisplayId = this.remoteDisplayFormView.$el.find('#itemTypeDeviceName').val();
        if (this.till != "") {
            $.ajax({
                url: '/data/delete-remote-display-till',
                type: 'POST',
                data: {
                    selectedTill: till,
                    remoteDisplayId: remoteDisplayId,
                    token: sessionToken
                },
                method: 'POST',
                success: function (data) {
                    M.toast({ html: '{Literal}Remote Display Till deleted successfully{/Literal}' });
                    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 deleting this Remote Display Till{/Literal}' });
                    }
                }
            });
        }
        else {
            M.toast({ html: '{Literal}There was an error deleting this till{/Literal}' });
        }
    },


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

        var name = this.remoteDisplayFormView.$el.find('#name').val();
        var address = this.remoteDisplayFormView.$el.find('#address').val();
        var pageWidth = this.remoteDisplayFormView.$el.find('#pageWidth').val();
        var templateName = this.remoteDisplayFormView.$el.find('#templateName').val();
        var deviceType = this.remoteDisplayFormView.$el.find('#device-type-dropdown').val();
        var isMonitor = false;
        if (deviceType == 'monitor') {
            isMonitor = true;
        }
        var userGroup = this.remoteDisplayFormView.$el.find('#user-group-dropdown option:selected').text();

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

        var itemTypeLength = 0;
        var itemTypes = []; 
        for (var i = 0; i < this.remoteDevices.length; i++) {
            if (this.remoteDevices[i].id == id) {
                itemTypeLength = this.remoteDevices[i].itemTypes.length;
                itemTypes = this.remoteDevices[i].itemTypes;
            }
        }

        var tillsLength = 0;
        var tills = []; 
        for (var i = 0; i < this.remoteDevices.length; i++) {
            if (this.remoteDevices[i].id == id) {
                tillsLength = this.remoteDevices[i].tills.length;
                tills = this.remoteDevices[i].tills;
            }
        }

        var updatedModel = {
            name: name,
            address: address,
            pageWidth: pageWidth,
            templateName: templateName,
            userGroup: userGroup,
            itemTypes: itemTypes,
            tills: tills,
            isMonitor : isMonitor,
            id: id
        }

        $.ajax({
            url: '/data/delete-remote-display-device',
            type: 'POST',
            data: {
                displayDevice: JSON.stringify(updatedModel),
                name: name,
                token: sessionToken
            },
            method: 'POST',
            success: function (data) {
                M.toast({ html: '{Literal}Remote Display Device deleted successfully{/Literal}' });
                that.getRemoteDevices();
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem deleting this Remote Display Device{/Literal}' });
                }
            }
        });
    },

    
     
    removeItemType: function (e) {
        var that = this;
        var sessionToken = this.getCookie();
        
        var element = $(e.currentTarget);
        var remoteDisplayId = $(element).attr('data-id');
        var itemTypeId = $(element).attr('item-type-id');

        $.ajax({
            url: '/data/delete-remote-display-item-type',
            type: 'POST',
            data: {
                remoteDisplayId: remoteDisplayId,
                itemTypeId: itemTypeId,
                token: sessionToken
            },
            method: 'POST',
            success: function (data) {
                M.toast({ html: '{Literal}Remote Display Device deleted successfully{/Literal}' });
                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 deleting this Remote Display Device{/Literal}' });
                }
            }
        });
    },

    loadModules: function (module) {
        var paramNames = Object.keys(module);
        var form = document.getElementById(module.moduleName);
        // var isActiveElement = form.querySelector('[data-name="isActive"]');
        // isActiveElement.checked = true;

        paramNames.forEach((p) => {
            var el = form.querySelector(`[data-name="${p}" i]`);
            if (el != null) {
                if (el.nodeName == "INPUT") {
                    if (el.type == "checkbox")
                        el.checked = module[p] == "true" || module[p] == true;
                    else {
                        el.value = module[p];
                    }
                } else if (el.nodeName == "SELECT") {
                    for (opt of el.children) {
                        if (opt.value == module[p]) {
                            opt.selected = "selected";
                        }
                    }
                }
                el.dataset.value = module[p];
            } else if(p.startsWith("Vat")) 
                this.addVatCodeForSageLive( '', module[p], p);
        });

        M.updateTextFields();
    },

    getModuleFormValues: function (moduleName) {
        var form = document.getElementById(moduleName);
        var module = { moduleName: moduleName };
        var email = "";

        for (el of form.elements) {
            if (el != null && el.dataset.name && !el.classList.contains('hide')) {
                if (el.nodeName == "INPUT") {
                    if (el.type == "checkbox"){
                            module[el.dataset.name] = el.checked ? "true" : "false";
                    }
                    else {
                        var regex = /Vat[1-99]/gi;
                        const value = el.value.trim();

                        if(el.dataset.name.includes('Email'))
                            email += value + ";";
                        else if(el.dataset.name.match(regex)){
                            var vatKey = value;
                            var vatValue = el.parentElement.nextElementSibling.firstElementChild.value;
                            module[el.dataset.name] = vatKey + ';' + vatValue;
                        }
                        else {
                            module[el.dataset.name] = value;
                        }
                    }
                } else if (el.nodeName == "SELECT") {
                    const value = el.selectedOptions[0]?.value;
                    if(typeof value !== 'undefined')
                        module[el.dataset.name] = value;
                }
            }
        }

        if(email != "")
            module["Email"] = email;

        return module;
    },

    getSettingsValues: function() {
        var settings = {};
        settings['Outputs.RemoteDisplayHandler'] = this.getModuleFormValues('Outputs.RemoteDisplayHandler');
        settings['Outputs.RemoteDisplay'] = this.getModuleFormValues('Outputs.RemoteDisplay');
        settings.dineInLabels = document.getElementById('dineInLabels').checked;
        settings.carryOutLabels = document.getElementById('carryOutLabels').checked;
        settings.deliveryLabels = document.getElementById('deliveryLabels').checked;

        return settings;
    },

    saveSettings: function() {
        var settings = this.getSettingsValues();

        $.ajax({
            url: '/data/save-remote-display-settings',
            type: 'POST',
            data: {
                settings: JSON.stringify(settings),
                token: this.getCookie()
            },
            method: 'POST',
            success: function (data) {
                M.toast({ html: '{Literal}Remote Display Settings saved successfully{/Literal}' });
                that.this.getRemoteDisplaySettings();
                // 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 Remote Display Settings{/Literal}' });
                }
            }
        });
    }
});