var ImportExportView = Backbone.View.extend({
    breadcrumb: {},
    tillList: [],
    sequenceList: [],
    hasAccess: false,
    sentTimes: [],
    datepicker: {},
    sequencePage: 1,
    statusLogRefreshInterval: null,

    events: {
        'click .importItems': 'importItems',
        'click .importCustomers': 'importCustomers',
        'click .importEmployees': 'importEmployeeModal',
        'click #reset-employee-pay-type-deny': 'importEmployees',
        'click #reset-employee-pay-type-confirm': 'importEmployeesReset', 
        'click .importReset': 'importReset',
        'click .exportSales': 'openSequenceModal',
        'click .exportItems': 'exportItems',
        'click .resendTimes': 'openDateModal',
        'click .send-times-button':'sendTimes',
        'click .sendTimes':'sendTimesToPayroll',
        'click .sendSequence' : 'openConfirmExportSequenceModal',
        'click #confirm' : 'exportSequence',
        'click #markAsExported' : 'markAsExported',
        'click .time-card' : 'toggleTimeCard',
        'click #filterSentTimes' : 'getSentTimes',
        'click #show-integration-status-logs-button': 'openIntegrationStatusLogsModal',
        'change #filterSequenceBy' : 'onFilterSequenceByChange',
        'click #skipSequencesNext' : 'onSkipSequencesNext',
        'click #skipSequencesPrev' : 'onSkipSequencesPrev',
    },

    initialize: async function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        await this.getTills();
        await this.getSequences();
        this.render();
    },

    render: function () {      
        var that = this;
        that.$el.html(that.template({
            sequences: that.sequenceList,
            sentTimes: that.sentTimes,
            sequencePage: that.sequencePage
        }));
       
        App.breadCrumbToolTip = "Import or export various things to or from your accounting program";
        App.setBreadcrumbs(this.breadcrumb);
        $(document).ready(function(){
            var elems = document.querySelectorAll('.tooltipped');
            var instances = M.Tooltip.init(elems);
            $('select').formSelect();
        });

        return this;
    },

    checkAccess: function () {
        var that = this;
        var sessionToken = getCookie();
        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_IMPORT),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.hasAccess = true;
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.hasAccess = false;
                }
            }
        });

        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_EXPORT),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.hasAccess = true;
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.hasAccess = false;
                }
            }
        });
    },

    getTills: async function () {
        var that = this;
        var sessionToken = getCookie();
        this.checkAccess();
        return $.ajax({
            url: '/data/get-tills-list',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: async function (data) {
                that.tillList = 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 data from the server{/Literal}'
                    });
                }
            }
        });
    },

    getSequences: async function () {
        var that = this;
        var sessionToken = getCookie();
        return $.ajax({
            url: '/data/get-all-sequences',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
               that.sequenceList = data.results;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });

        that.$el.find('select').formSelect();
    },

    openSequenceModal: function () {
        $('#import-sequence-modal').modal().modal('open');
    },

    importItems: function () {
        var element = document.querySelector('.importItems');
        if (this.hasAccess) {
            if(this.checkActionInProgress(element))
                return;
            var that = this;
            var sessionToken = getCookie();
            that.addSpinner(element);
            
            $.ajax({
                url: '/data/import-items',
                type: 'POST',
                data: {
                    token: sessionToken
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Items Import Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {  
                        M.toast({ html: '{Literal}Import Inventory Request Failed. A current Inventory Import may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Import Items{/Literal}' });
        }
        
    },

    importCustomers: function () {
        var element = document.querySelector('.importCustomers');
        if (this.hasAccess) {
            if(this.checkActionInProgress(element))
                return;
            var that = this;
            var sessionToken = getCookie();
            that.addSpinner(element);
            $.ajax({
                url: '/data/import-customers',
                type: 'POST',
                data: {
                    token: sessionToken
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Customers Import Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Import Customer Request Failed. A current Customer Import may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Import Customers{/Literal}' });
        }
        
    },

    importEmployeeModal: function () {
        $('#import-employee-modal').modal().modal('open');
    },

    importEmployees: function () {
        var that = this;
        var element = document.querySelector('.importEmployees');
        if (this.hasAccess) {
            if(this.checkActionInProgress(element))
                return;
            var sessionToken = getCookie();
            that.addSpinner(element);
            $.ajax({
                url: '/data/import-employees',
                type: 'POST',
                data: {
                    resetOnImport: "false",
                    token: sessionToken,
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Employees Import Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Import Employee Request Failed. A current Employee Import may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Import Employees{/Literal}' });
        }
    },

    importEmployeesReset: function () {
        var that = this;
        var element = document.querySelector('.importEmployeesReset');
        if (this.hasAccess) {
            if(this.checkActionInProgress(element))
                return;
            var sessionToken = getCookie();
            that.addSpinner(element);
            $.ajax({
                url: '/data/import-employees',
                type: 'POST',
                data: {
                    resetOnImport: "true",
                    token: sessionToken,
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Employees Import Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Import Employee Request Failed. A current Employee Import may be in progress or check that the Accounting and adapter software are running.{/Literal}' });                    
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Import Employees{/Literal}' });
        }
    },

    importReset: function () {
        var element = document.querySelector('.importReset');
        if (this.hasAccess) {
            var that = this;
            if(this.checkActionInProgress(element))
                return;
            var sessionToken = getCookie();
            that.addSpinner(element);
            $.ajax({
                url: '/data/import-reset',
                type: 'POST',
                data: {
                    token: sessionToken,
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Import Reset Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Import Reset Request failed. Check that the adapter software is running.{/Literal}' });
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Reset Import{/Literal}' });
        }
        
    },

    exportSales: function () {
        var that = this;
        var element = document.querySelector('.exportSales');
        if (this.hasAccess) {
            if(this.checkActionInProgress(element))
                return;
            var sessionToken = getCookie();
            that.addSpinner(element);
            $.ajax({
                url: '/data/export-sales',
                type: 'POST',
                data: {
                    token: sessionToken,
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Sales Export Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Export Sales Request Failed. A current Employee Export may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Export Sales{/Literal}' });
        }
    },

    exportItems: function () {
        var that = this;
        var element = document.querySelector('.exportItems');
        if (this.hasAccess) {
            if(this.checkActionInProgress(element))
                return;
            var sessionToken = getCookie();
            that.addSpinner(element);
            $.ajax({
                url: '/data/export-items',
                type: 'POST',
                data: {
                    token: sessionToken
                },
    
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
    
                    M.toast({ html: '{Literal}Items Export Started{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Export Items Request Failed. A current Items Export may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                    }
                },
                complete: function(e) {
                    that.removeSpinner(element);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}You do not have access to Export Items{/Literal}' });
        }
    },

    openDateModal: function() {
        var that = this;
        var element1 = document.querySelector('.sendTimes');
        var element2 = document.querySelector('.resendTimes');
        if(this.checkActionInProgress(element1) || this.checkActionInProgress(element2))
            return;
        var pickerElement = document.querySelectorAll('.datepicker');
        var instances = M.Datepicker.init(pickerElement, {
            autoClose: true,
            container: 'body',
            i18n: App.i18n,
        });

        var today = new Date();
        instances[3].setDate(today);
        this.$el.find('#thruDate').val(today.toLocaleDateString(window.navigator.languages[0]));
        var firstDayofTheMonth = new Date(new Date(new Date().setDate(1)).setHours(0,0,0));
        instances[2].setDate(firstDayofTheMonth);
        this.$el.find('#fromDate').val(firstDayofTheMonth.toLocaleDateString(window.navigator.languages[0]));
        this.datepicker = instances;
        $('#send-times-modal').modal().modal('open');
        this.getSentTimes();
    },

    sendTimesToPayroll: function() 
    {
        var element1 = document.querySelector('.sendTimes');
        var element2 = document.querySelector('.resendTimes');
        if(this.checkActionInProgress(element1) || this.checkActionInProgress(element2))
            return;
        var that = this;
        var sessionToken = getCookie();
        that.addSpinner(element1);
        that.addSpinner(element2);
        $.ajax({
            url: '/data/send-times-payroll',
            type: 'POST',
            data: {
                token: sessionToken
            },

            success: function (data) {
                var success = false;
                if (typeof data.success !== 'undefined') {
                    success = data.success;
                }

                if(success)
                    M.toast({ html: '{Literal}Times Export Started{/Literal}'});
                else
                    M.toast({ html: '{Literal}Export Times Request Failed. A current Times Export may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Export Times Request Failed. A current Times Export may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                }
            },
            complete: function(e) {
                that.removeSpinner(element1);
                that.removeSpinner(element2);
            }
        });
    },

    getSentTimes: async function() {
        var that = this;
        var sessionToken = getCookie();
    
        var fromDate = this.datepicker[2].date;
        var thruDate = this.datepicker[3].date;

        return $.ajax({
            url: '/data/get-sent-times',
            type: 'POST',
            data: {
                fromDate: fromDate.setHours(0,0,0),
                thruDate: thruDate.setHours(23,59,59),
                token: sessionToken
            },

            success: function (data) {
                that.sentTimes = data.sentTimes;
                that.renderSentTimes();
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Error getting sent times{/Literal}' });
                }
            }
        });

    },

    sendTimes: function() {
        var sessionToken = getCookie();
        var timesToSend = [];
        this.$el.find("#sentTimesList .time-card[selected]").each( (index, element) => {
             timesToSend.push(element.getAttribute("data-time"))
        });

        if(timesToSend.length > 0) {
            var that = this;
            var element1 = document.querySelector('.sendTimes');
            var element2 = document.querySelector('.resendTimes');
            var sessionToken = getCookie();
            that.addSpinner(element1);
            that.addSpinner(element2);
            $("#send-times-modal").modal('close');

            $.ajax({
                url: '/data/resend-times-payroll',
                type: 'POST',
                data: {
                    sentTimes: JSON.stringify(timesToSend),
                    token: sessionToken
                },

                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }

                    M.toast({ html: '{Literal}Times Export Started{/Literal}' });
                },
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Export Times Request Failed. A current Times Export may be in progress or check that the Accounting and adapter software are running.{/Literal}' });
                    }
                },
                complete: function() {
                    that.removeSpinner(element1);
                    that.removeSpinner(element2);
                }
            });
        }
        else {
            M.toast({ html: '{Literal}Not selected any time records{/Literal}' });
        }
    },

    openConfirmExportSequenceModal: function (e) {
        var that = this;
        var element = $(e.currentTarget);
        var sequenceId = $(element).attr("data-id");
        var tillId = $(element).attr("till-id");
        var modalElement = document.getElementById('confirm-resend-modal');
        modalElement.dataset['id'] = sequenceId;
        modalElement.dataset['tillId'] = tillId;
        var modal = M.Modal.init(modalElement);
        modal.open();
        
    },

    exportSequence: function () {
        var modalElement = document.getElementById('confirm-resend-modal');
        var sequenceId = modalElement.dataset.id;
        var tillId = modalElement.dataset.tillId;
        var sessionToken = getCookie();

        $.ajax({
            url: '/data/export-sales',
            type: 'POST',
            data: {
                till: tillId,
                sequence: sequenceId,
                token: sessionToken
            },

            success: function (data) {
                var success = false;
                if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                    success = data.results.success;
                }

                M.toast({ html: '{Literal}Sales Export Started{/Literal}' });
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Export Sales Request Failed. A current Sales Export may be in progress or check that the Accounting and adapter software are running.{/Literal}.' });
                }
            }
        });
    },
    
    toggleTimeCard: function(event) {
        $(event.target).toggleClass("blue-grey lighten-4");
        event.target.toggleAttribute('selected');
    },

    renderSentTimes: function() {
        this.$el.find("#sentTimesList").html("");
        var cards = "";
        this.sentTimes.forEach(time => {
          cards +=  `<div class="row" >
            <div class="col s12 m6 offset-m3">
                <div class="card-panel waves-effect waves-light time-card" data-time=${time} >
                    <span class="">${ new Date(time).toLocaleString(window.navigator.languages)}</span>
                </div>
            </div>
        </div>`
        });
        
        this.$el.find("#sentTimesList").append(cards);
    },

    getIntegrationStatusLogs: async function() {
        var sessionToken = getCookie();
        var that = this;
        return $.ajax({
            url: '/data/get-integration-status-logs',
            type: 'POST',
            data: {
                token: sessionToken
            },

            success: function (data) {
                var success = false;
                if (typeof data !== 'undefined' && typeof data.success !== 'undefined') {
                    if(data.success)
                        that.statusLogList = data.integrationStatusLogs;
                }
                else
                    M.toast({ html: '{Literal}Something went wrong while getting status logs.{/Literal}.' });
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Something went wrong while getting status logs.{/Literal}.' });
                }
            }
        });
    },

    openIntegrationStatusLogsModal: async function(e, reload) {
        var tbody = document.querySelector('#integration-status-logs-table tbody');
        await this.getIntegrationStatusLogs();
        this.statusLogList  = this.statusLogList.sort( (a,b) => {
            if(a.timestamp > b.timestamp)
                return -1;
            else if(a.timestamp < b.timestamp)
                return 1;
            else
                return 0;
        });

        var tr = '';
        this.statusLogList.forEach( log => {
            tr += '<tr>'
            tr += '<td>' + toDateTimeString(log.timestamp) + '</td>';
            tr += '<td>' + log.action + '</td>';
            tr += '<td>' + log.statusCode + '</td>';
            tr += '<td>' + log.status + '</td>';
            tr += '<td>' + log.message + '</td>';
            tr += '</tr>';
        })

        tbody.innerHTML = tr;

        var modalElement = document.getElementById('integration-status-logs-modal');
        if(!reload) {   
            var modal = M.Modal.init(modalElement, {
                onCloseEnd: () =>  { clearInterval(this.statusLogRefreshInterval);}
            });
            modal.open();
            
            this.statusLogRefreshInterval = setInterval(() => {
                this.openIntegrationStatusLogsModal(undefined, true);
            }, 5000); 
        }
    },

    onFilterSequenceByChange: function() {
        var selected = document.getElementById('filterSequenceBy').value;
        var sequenceElementList = document.querySelectorAll('.sequence-card-root');
        var showSentToAccounting = selected == 'sentToAccounting';
        if(selected != 'all') {
            sequenceElementList.forEach(el => {
                var thisElSentToAccounting = el.dataset.senttoaccounting == showSentToAccounting.toString();
                if(!thisElSentToAccounting)
                    el.style.display = 'none';
                else
                    el.style.display = 'block';
            })
        }
        else {
            sequenceElementList.forEach(el => {
                el.style.display = 'block';
            });
        }
    },
    onSkipSequencesNext: function(e) {
        if(this.sequencePage < this.sequenceList.length / 100) {
            
            this.sequencePage++;
            this.render();
            this.openSequenceModal();
        }
    },
    onSkipSequencesPrev: function(e) {
        if(this.sequencePage > 1) {
            
            this.sequencePage--;
            this.render();
            this.openSequenceModal();
        }
    },

    addSpinner: function(el) {
        var spinnerHtml = ` <div class="preloader-wrapper big active edit">
        <div class="spinner-layer spinner-blue-only">
          <div class="circle-clipper left">
            <div class="circle"></div>
          </div><div class="gap-patch">
            <div class="circle"></div>
          </div><div class="circle-clipper right">
            <div class="circle"></div>
          </div>
        </div>
      </div>`;

        if(el != null) {
            el.insertAdjacentHTML('beforeend', spinnerHtml);
            el.dataset.inproggress = true;
        }
    },

    removeSpinner: function(element) {
        var el = element.querySelector('.preloader-wrapper.big.active.edit');
        if(el != null) {
            el.remove();
            element.dataset.inproggress = false;
        }
    },

    checkActionInProgress(element) {
        return element.dataset.inproggress == 'true';
    },

    markAsExported: function(e) {
        var that = this;
        var sessionToken = getCookie();
        var modalElement = document.getElementById('confirm-resend-modal');
        var sequenceId = modalElement.dataset.id;
        var tillId = modalElement.dataset.tillId;

        $.ajax({
            url: '/data/mark-sequence-exported',
            type: 'POST',
            data: {
                token: sessionToken,
                sequence: sequenceId,
                till: tillId
            },
            success: function (data) {
                var success = false;
                if (typeof data.success !== 'undefined' && data.success === true) {
                    M.toast({ html: '{Literal}Sequence marked as exported{/Literal}' });
                    
                    var cardEl = document.querySelector(`.sendSequence[data-id="${sequenceId}"][till-id="${tillId}"] .exported`);
                    cardEl.innerText = '{Literal}Yes{/Literal}';
                }
                else
                    M.toast({ html: '{Literal}There was a problem marking this sequence as exported{/Literal}' });
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem marking this sequence as exported{/Literal}' });
                }
            }
        });

    }
});
