var RoomsTablesView = Backbone.View.extend({
    breadcrumb: {},
    gridSizeRows: 7,
    gridSizeCols: 11,
    occupiedCells: {},
    selectedTableDiv: null,
    selectedTable: null,
    addTable: null,
    currentRoom: "",
    lastX: -72,
    lastY: 0,

    events: {
        'click .edit-modal-trigger': 'openEditModal',
        'click .delete-modal-trigger': 'openDeleteModal',
        'change #key-set-selector' : 'changePage',
        'click #addRoomButton' : 'addNewPage',
        'click  .drag-list li' : 'openNewTableOption',
        'click .add-table-button' : 'addTable',
        'click .table' : 'showNameOptions',
        'click #deleteTable' : 'deleteTable',
        'keyup #editTableText' : 'changeTableText',
        'click .save-new-room-button' : 'saveNewRoom',
        'click .save-room-button': 'saveRoom',
        'click #delete-room-button': 'deletedRoom',
        'click #editRoomName': 'openEditNameModal',
        'click .save-room-name-button' : 'saveRoomName',
        'click .new-table' : 'addNew',
        'click #rotateRight, #rotateLeft' : 'rotateTable'
    },

    tableTypes: { 
        "Bar-1": {width: 42,height: 30},
        "BarL-1": {width: 42,height: 30},
        "BarR-1": {width: 42,height: 30},
        "Square-2": {width: 30,height: 52},
        "Square-4": {width: 57,height: 52},
        "Rectangle-4": {width: 52,height: 52},
        "Rectangle-6": {width: 69,height: 52},
        "Oval-6": {width: 71,height: 59},
        "Round-4": {width: 54,height: 52},
        "Round-6": {width: 62,height: 61},
        "Round-8": {width: 69,height: 69}
    },

    dataChangedAndNotSaved: false,

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


    getTables: function () {
        var that = this;
        var sessionToken = getCookie();
        $.ajax({
            url: '/data/get-tables',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.tables = data.tables;
                that.rooms = data.rooms

                var collection = new RoomsTablesCollection();
                for (var i = 0; i < data.tables.length; i++) {
                    var currentTable = data.tables[i];
                    collection.add(new RoomsTables(currentTable));
                }
                
                that.fullCollection = collection;
                that.collection.set(collection.models);
                //that.$el.find('#page-selector').formSelect();
                that.currentRoom = that.rooms[0];

               
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Occurred a problem while rendering this page{/Literal}' });
                }
            }
        });
    },
    
    openEditModal: function (e) {
        this.editModal.modal('open');
    },

    openDeleteModal: function (e) {
        var deleteRoomModal = this.$el.find('#delete-room-modal').modal();
        deleteRoomModal.modal('open');
    },

    render: function () {
        var that = this;
        $('select').formSelect();

        that.$el.html(that.template({
            tables: that.collection.models,
            rooms: that.rooms,
            pages: that.pages
        }));
        $(document).ready(function () {
            $('.fixed-action-btn').floatingActionButton();
            $('.tooltipped').tooltip();
            $('select').formSelect();
            $('#droppable').empty();
            var roomDiv = document.getElementById('droppable');

            $('.new-table').draggable({
                revert: "invalid",
                helper: 'clone',
                cursorAt: { left: 0, top:0 },
                distance: 10
            });

            $('#droppable').droppable({
                accept: ".new-table",
                drop: function(event, ui) {
                    // var droppable = $(this);
                    // var draggable = ui.draggable;
                    var room = that.$el.find('#key-set-selector option:selected').text();
                    var type = ui.draggable[0].id;
                    var newTableName = room.slice(0, 7);
                    var newDiv = document.createElement('div');
                    var roomTablesLen = that.tables.filter( t => t.room == room).length;
                    if(roomTablesLen == 0)
                        roomTablesLen += 1;
                    
                    newTableName = that.getNextTableName();
                    var newDivId = 'divTable' + roomTablesLen;

                    newDiv.setAttribute('id', newDivId);
                    // $(this).removeClass("selectedTable");

                    var rect = document.getElementById('droppable').getBoundingClientRect();
                    var x = event.clientX - rect.left; 
                    var y = event.clientY - rect.top;
      
                    
                    var addedTable = {
                        id: 0,
                        name: newTableName,
                        room: room,
                        type: type,
                        turn: 0,
                        X: x,
                        Y: y,
                        isAdded: true
                    }

                    that.tables.push(addedTable);
                    

                    newDiv.style.position = "absolute";
                    newDiv.style.left = addedTable.X + 'px';
                    newDiv.style.top = addedTable.Y + 'px';
                    newDiv.style.transform = 'rotate(' + 0 +'deg) scale(0.85)';
                    var newHTML = '<span id="draggable" class="drag"><img class="table" src="img/' + type + '.png" width="' + that.tableTypes[type].width + '" height="' + that.tableTypes[type].height + '" data-id="' + newDivId + '" ><br><span id="' + newDivId + 'Text" class="tableText">' + addedTable.name + '</span></span>';
                    newDiv.innerHTML = newHTML;
                    roomDiv.appendChild(newDiv);
                    document.getElementById(newDivId).addEventListener(newDivId, that.showNameOptions);
                    
                    // mousePos = that.mouseCoords(event);
                   
                    that.addDraggableElement(newDivId, type);
                }
              });


              that.renderTables();

            $('select').formSelect();
        });
        App.breadCrumbToolTip = "Edit and save your room and table setup that will be used on your POS."; 
        App.setBreadcrumbs(this.breadcrumb);

        return this;
    },

    renderTables: function() {
        var that = this;
        this.lastX= -72;
        this.lastY= 0;
        var roomDiv = document.getElementById('droppable');

        if(!that.rooms || !that.tables)
            return;

        var numTables = that.tables.length;

        for (i = 0; i < numTables; i++)
        {
            if (that.tables[i].room == that.currentRoom)
            {
                var newDiv = document.createElement('div');
                var newDivId = "divTable" + i;
                newDiv.setAttribute('id', newDivId);

                var x = parseInt(that.tables[i].X);
                var y = parseInt(that.tables[i].Y);
                var rotate = parseInt(that.tables[i].turn);

                newDiv.style.position = "absolute";
                newDiv.style.left = x + 'px';
                newDiv.style.top = y + 'px';
                newDiv.style.transform = 'rotate(' + rotate +'deg) scale(0.85)';
                var tableType = that.tables[i].type;

                var newHTML = '<span id="draggable" class="drag"><img class="table" src="img/' + tableType + '.png" width="' + that.tableTypes[tableType].width + '" height="' + that.tableTypes[tableType].height + '" data-id="' + newDivId + '" ><br><span id="' + newDivId + 'Text" class="tableText">' + that.tables[i].name + '</span></span>';
                
                newDiv.innerHTML = newHTML;
                roomDiv.appendChild(newDiv);
                selectedTableDiv = document.getElementById(newDivId);
                
                that.addDraggableElement(newDivId, tableType);

            }
        }
    },

    mouseCoords: function (ev) {
        // FireFox and Chrome coordinates
        if(ev.pageX || ev.pageY)
            return {x:ev.pageX, y:ev.pageY};

        // IE coordinates
        return {x:ev.clientX, y:ev.clientY};
    },

    moveRoomTable: function(selectedTableDiv) {
        var tableName = selectedTableDiv.querySelector('span').textContent;
        var tables = this.tables;
        // var divId = selectedTableDiv.id;
        // var tableNumber = divId.substring(8);
        var x = selectedTableDiv.style.left;
        var y = selectedTableDiv.style.top;
        x = x.replace('px', '');
        y = y.replace('px', '');
        x = Number.parseInt(x);
        y = Number.parseInt(y);
        var thisTable = tables.find( t => t.name == tableName);
        thisTable.X = "" + x;
        thisTable.Y = "" + y;
        thisTable.updated = "true";
        this.clearSelected(selectedTableDiv);
    },

    clearSelected: function (selectedTableDiv) {
        var newDivId = "";
        for (i = 0; i < this.tables.length; i++)
        {
            $("#divTable" + i).removeClass("selectedTable");
        }
        
        $('#addTableOptions').hide();
        $('#editTableOptions').hide();
        var tableControls = document.getElementById('tableControls');
        if(tableControls != null)
            tableControls.remove();
    },

    changePage: function () {
        this.newlyAddedRoomTablesCount = 0;
        var roomDiv = document.getElementById('droppable');
        roomDiv.innerHTML = '';
        this.currentRoom = document.getElementById('key-set-selector').value;
        this.renderTables();
    },

    validateTableName: function() {
        var that = this;
        var tableName = this.$el.find('#addTableText').val();
        var isValid = true;
        if (tableName!= "") {
            var tablesLen = that.tables.length;
            
            for (i = 0; i < tablesLen; i++) {
                if (tableName == that.tables[i].name) {
                    M.toast({ html: '{Literal}This name is already defined{/Literal}' });
                    isValid = false;
                    break;
                }
            }
        }
        else {
            isValid = false;
            M.toast({ html: '{Literal}Please enter a table name{/Literal}' });
        }  

        if(tableName.length > 10) {
            isValid = false;
            M.toast({ html: '{Literal}Table name is longer than 10 characters{/Literal}' });
        }

        return isValid;
    },
    
    addTable: function (e) {
        var that = this;
        var tableName = this.$el.find('#addTableText').val();
        var newDiv = document.createElement('div');
        if (this.validateTableName()) {
            if (this.addTable != null) {
                var tableId = this.addTable;
                var tablesLen = that.tables.length;

                var roomDiv = document.getElementById('droppable');
                var newDiv = document.createElement('div');
                var newDivId = "divTable" + tablesLen;
                newDiv.setAttribute('id', newDivId);


                var tableType = document.querySelector('.selectedNewTable').id;
                var x = this.lastX + 72;
                var y = this.lastY;
                if(x > 800 - 72 ) {
                    x = 0;
                    y += 80;
                }

                this.lastX = x;
                this.lastY = y;
                newDiv.style.left = x +'px';
                newDiv.style.top = y + 'px';
                newDiv.style.position = 'absolute';
                newDiv.style.transform = 'rotate(0deg) scale(0.85)';

                var newHTML = '<span id="draggable" class="drag"><img class="table" src="img/' + tableType + '.png" width="' + that.tableTypes[tableType].width + '" height="' + that.tableTypes[tableType].height + '" data-id="' + newDivId + '" ><br><span id="' + newDivId + 'Text" class="tableText">' + tableName + '</span></span>';

                newDiv.innerHTML = newHTML;
                roomDiv.appendChild(newDiv);
                var room = that.$el.find('#key-set-selector option:selected').text();

                var addedTable = {
                    id: 0,
                    name: tableName,
                    room: room,
                    type: tableType,
                    turn: 0,
                    X: x,
                    Y: y,
                    isAdded: true
                }

                this.tables.push(addedTable);
                this.addTable = null;
                this.newlyAddedRoomTablesCount++;
                this.addDraggableElement(newDivId, tableType)
            }
        }
    },

    addDraggableElement: function(elementId, type) {
        var that = this;

        var element = $('#'+elementId).draggable({
            // cursorAt: { left: x, top:y },
            containment: $('.roomDisplay'),
            drag: function () {
                //that.tableSelected(this);
                $(this).addClass("selectedTable");
            },
            preventCollision: true,
            stop: function (event, ui) {
                // mousePos = that.mouseCoords(event);
                that.cleanTableSelection();
                that.moveRoomTable(this);
            },
        });
    },

    showNameOptions: function (e) {
        var that = this;
        var room = this.$el.find('#key-set-selector option:selected').text();
        var element = e.target;
        var selectedDiv = document.getElementById(element.dataset.id);
        var newDivId = "";
        $('#addTableOptions').hide();
        $('#editTableOptions').show();

        // const draggableDivs = document.querySelectorAll('#droppable > .ui-draggable');
        // for (const draggable of draggableDivs) {
        //     draggable.classList.remove('selectedTable');
        // }

        that.cleanTableSelection();

        var tableName = selectedDiv.querySelector('.tableText').innerText;

        that.selectedTable = that.tables.find( t => t.room == room && t.name == tableName)
        var editTableText = document.getElementById("editTableText");
        selectedDiv.classList.add("selectedTable");
        editTableText.value = that.selectedTable.name;


        var tableControls = `<div id="tableControls" style="display: none; position: absolute; padding:20px; background:#00000078;">
        <button class="waves-effect waves-light btn red" id="rotateLeft"><i class="material-icons large">rotate_left</i></button>
        <button class="waves-effect waves-light btn" id="rotateRight"><i class="material-icons large">rotate_right</i></button>
    </div>`;


        document.getElementById('droppable').insertAdjacentHTML('beforeend', tableControls);

        var tableControls = document.getElementById('tableControls');
        tableControls.style.display = 'block';
        var top = Number.parseInt(selectedDiv.style.top.replace('px', ''));
        // var left = Number.parseInt(selectedDiv.style.left.replace('px', ''));
        tableControls.style.top = (top + 80) + 'px';
        tableControls.style.left = selectedDiv.style.left

    },

     
    openNewTableOption: function (e) {
        const draggingNow = document.querySelector('.ui-draggable-dragging');
        if(draggingNow != null)
            return;
        $('#addTableOptions').show();
        $('#editTableOptions').hide();
        var that = this;
        var tableType = e.currentTarget.querySelector('.new-table').id;
        this.addTable = e.currentTarget.id;
        var imgElement = e.currentTarget.querySelector('img')

        var addTableName = document.getElementById("addTableText");

        addTableName.value = this.getNextTableName();

        // Selects the button to add from menu
        this.cleanTableSelection();

        imgElement.src = 'img/' + tableType + 'Selected.png';
        imgElement.parentElement.classList.add('selectedNewTable');

        
        var room = this.$el.find('#key-set-selector option:selected').text();
        var numTables = that.tables.length;

        
    },

    getNextTableName: function() {
        var that = this;
        var room = this.$el.find('#key-set-selector option:selected').text();
        var newTableName = room.slice(0, 7);

        var roomTablesLen = that.tables.filter( t => t.room == room).length;
        if(roomTablesLen == 0)
            roomTablesLen += 1;

        var tableExists = true;
        while(tableExists) {
            const foundTable = that.tables.find(t => {
                const split = t.name.split('-');
                var tableNum = split[0];
                if(isNaN(parseInt(tableNum)))
                    tableNum = split[1];
                if(tableNum != undefined)
                    return tableNum.padStart(2, '0') == (roomTablesLen.toString().padStart(2, '0'))
            })

            if(foundTable)
                roomTablesLen++;
            else
                tableExists = false;
        }

        
        return roomTablesLen.toString().padStart(2, '0') + '-' + newTableName;
    },

    cleanTableSelection: function() {
        const newTableElements = document.querySelectorAll('#drag-list .new-table');
        for (const el of newTableElements) {
            const thisTableType = el.id;
            el.querySelector('img').src = 'img/' + thisTableType + '.png';
            el.classList.remove('selectedNewTable');
        }

        const tableElements = document.querySelectorAll('.selectedTable');
        for (const el of tableElements) {
            el.classList.remove('selectedTable');
        }
    },

    changeTableText: function() {
        var that = this;
        var newDivId = "";
       

        if (this.selectedTable != null) {
            var tableName = this.$el.find('#editTableText').val();
            var existingTable = that.tables.find( t => {
                return t.name === tableName && t.id !== this.selectedTable.id;
            })
            if(existingTable !== undefined) {
                M.toast({ html: '{Literal}This name is already defined{/Literal}' });
                return;
            }
            var numTables = that.tables.length;
            for (i = 0; i < numTables; i++)
            {
                if (that.tables[i].name == this.selectedTable.name && that.tables[i].id == this.selectedTable.id)
                {
                    var newTable = that.tables[i];
                    newDivId = "divTable" + i;
                    selectedTableDiv = document.getElementById(newDivId + 'Text');
                    selectedTableDiv.innerHTML = tableName;
                    newTable.name = tableName;
                    this.selectedTable = newTable;
                    that.tables[i] = newTable;                    
                }
            }
        }
    },

    saveRoom: function () {
        var room = this.$el.find('#key-set-selector').val(); 
        var success = true;

        if (room != "newRoom") {
            var that = this;
            var sessionToken = getCookie();
            var savedRoom = [];

            for (var i = 0; i < this.tables.length; i++) {
                
                if (this.tables[i].room == room) {
                    savedRoom.push(this.tables[i]);
                }
            }
            
            $.ajax({
                url: '/data/save-room',
                data: {
                    tables: JSON.stringify({tables: savedRoom}),
                    roomName: (room),
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
    
                success: function (data) {
                    that.tables.forEach( t => {
                        if(t.isAdded)
                            t.isAdded = false;
                    })

                    if (data.success)
                        M.toast({ html: '{Literal}Room updated successfully{/Literal}' });

                    that.getTables();
                },
    
                error: function (e) {
                    M.toast({ html: '{Literal}Error: Room not updated{/Literal}' });

                    success = false;
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                }
            });
            
        }
        else {
            M.toast({ html: '{Literal}Please Choose A Valid Room{/Literal}' });
        }
    },
    
    saveNewRoom: function () {
        var newRoomName = this.$el.find('#newRoomName').val();

        if (newRoomName == "") {
            M.toast({ html: '{Literal}A Room Name Must Be Defined{/Literal}' });
        }
        else {
            var foundName = false;
            for (var i = 0; i < this.rooms.length; i++) {
                if (this.rooms[i] == newRoomName) {
                    foundName = true;
                }
            }

            if (foundName == true) {
                M.toast({ html: '{Literal}This Room Name Is Already Defined{/Literal}' });
            }
            else {
                this.rooms.unshift(newRoomName);
                this.currentRoom = newRoomName;
                this.render();
            }
        }
    },

    deletedRoom: function () {
        var that = this;
        var sessionToken = getCookie();
        
        $.ajax({
            url: '/data/remove-room',
            data: {
                roomName: (that.currentRoom),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.render();
                M.toast({ html: '{Literal}Room removed successfully{/Literal}' });

                for (i = 0; i < that.tables.length; i++)
                {
                    if (that.tables[i].room == that.currentRoom)
                    {
                        that.tables[i] = "";
                        newDivId = "divTable" + i;
                        $('#' + newDivId).remove();
                    }
                }

                
                for (i = 0; i < that.pages.length; i++)
                {
                    if (that.rooms[i] == that.currentRoom)
                    {
                        that.rooms[i] = "";
                    }
                }
                that.changePage();
            },

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

    deleteTable: function () {
        var that = this;
        var sessionToken = getCookie();
        var tableName = this.selectedTable.name;
        var room = this.selectedTable.room;

        if(this.selectedTable.isAdded) {
            that.tables = that.tables.filter( t => !(t.room == that.selectedTable.room  && t.name == that.selectedTable.name) );
            $('.selectedTable').remove();
            that.clearSelected();
        }
        else {
            $.ajax({
                url: '/data/remove-table',
                data: {
                    tableName: tableName,
                    room: room,
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',

                success: function (data) {
                    that.tables = that.tables.filter( t => !(t.room == that.selectedTable.room  && t.name == that.selectedTable.name) );
                    $('.selectedTable').remove();
                    that.clearSelected();
                    M.toast({ html: '{Literal}Table removed 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 deleting this table{/Literal}' });
                    }
                }
            });
        }
    },

    addNewPage: function () {
        var newRoomModal = this.$el.find('#new-room-form-modal').modal();
        newRoomModal.modal('open');
    },

    openEditNameModal: function () {
        var roomName = document.getElementById('roomName'); 
        roomName.value = this.currentRoom;

        var roomNameModal = this.$el.find('#edit-room-name-modal').modal();
        roomNameModal.modal('open');
    },

    saveRoomName: function () {
        var that = this;
        var newRoomName = this.$el.find('#roomName').val();
        var currentRoomName = this.currentRoom;
        var sessionToken = getCookie();
        if (currentRoomName == "main" || currentRoomName == "ראשי") {
            M.toast({ html: '{Literal}The room "main" cannot be changed{/Literal}' }); 
        }
        else {
            $.ajax({
                url: '/data/rename-room',
                data: {
                    oldRoomName: currentRoomName,
                    newRoomName: (newRoomName),
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
    
                success: function (data) {
                    for (var i = 0; i < that.rooms.length; i++) {
                        if (that.rooms[i] == currentRoomName) {
                            that.rooms[i] = newRoomName;
                        }
                    }

                    for (var i = 0; i < that.tables.length; i++) {
                        if (that.tables[i].room == currentRoomName) {
                            that.tables[i].room = newRoomName;
                        }
                    }
                    that.render();
                    M.toast({ html: '{Literal}Room name 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 renaming this room{/Literal}' });
                    }
                }
            });
        }
    },

    rotateTable: function(e) {
        var that = this;
        var newTurn = this.selectedTable.turn;
        if(e.currentTarget.id == 'rotateRight')
            newTurn += 45;
        else if(e.currentTarget.id == 'rotateLeft')
            newTurn -= 45;
        newTurn += 360;
        newTurn %= 360;
        this.selectedTable.turn = newTurn;
        
        if (this.selectedTable != null) {
            
            var numTables = that.tables.length;
            for (i = 0; i < numTables; i++) {
                if (that.tables[i].name == this.selectedTable.name && that.tables[i].id == this.selectedTable.id) {                   
                    that.tables[i].turn = newTurn;
                    var tableEl = document.getElementById('divTable' + i);
                    tableEl.style.transform = 'rotate(' + newTurn +'deg) scale(0.85)';
                    return;               
                }
            }
        }
        
    },
});