var QBOView = Backbone.View.extend({
    events: {
        'click #connectToQbo': 'openQBO',
        'click #disconnectQBO': 'disconnectQBO'
    },

    breadcrumb: {},

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        this.model = options.model;
        this.listenTo(this.model, 'change', this.render);
        this.checkQBOConnection();
    },

    render: function () {
        var that = this;
        this.$el.html(this.template());
        App.breadCrumbToolTip = "Connect to QuickBooks Online"; 
        App.setBreadcrumbs(this.breadcrumb);
                
        return this;
    },

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

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

        $.ajax({
            url: '/data/check-qbo-status',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                if (data.grantUrl == "alreadyConnected") {
                    $('#disconnectBlock').show();
                    $('#qbo-block').hide();
                }
                else {
                    $('#qbo-block').show();
                    $('#disconnectBlock').hide();
                }
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}An error has occured{/Literal}' });
                }
            }
        });
    },

    openQBO: function() {
        var sessionToken = this.getCookie();
        var that = this
        $.ajax({
            url: '/data/connect-to-qbo',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                
                if (data.state != "" && data.serial != "" && data.cient_id != "" && data.combineKey != "") 
                {
                    var winName='Connect to QBO';
                    var left = (screen.width/2)-(844/2);
                    var top = (screen.height/2)-(1024/2);

                    var url = "https://accupos-cloud.appspot.com/openQBO?serial=" + data.serial + "&client_id=" + data.client_id + "&state=" + data.state + "&combinedKey=" + data.combinedKey;
                    var windowoption='resizable=yes,height=844,width=1024, left='+ left + ', top=' + top + 'location=0,menubar=0,scrollbars=1';
                    var win = window.open(url, winName, windowoption);
                    win.focus();
                    that.sendResponse();
                }
                setTimeout(function() { 
                    var MyApp = new Backbone.Router();
                    MyApp.navigate('home', {trigger: true}); 
                }, 5000);

            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}An error has occured{/Literal}' });
                }
            }
        });
    },

    sendResponse: function () {
        /*const delay = ms => new Promise(res => setTimeout(res, ms));
        delay(30000);
        debugger;
        var sessionToken = this.getCookie();
        var that = this
        var url = "https://nodejswebsocket.appspot.com/checkForFinishedConnection"
        
        var xhttp = new XMLHttpRequest();
        xhttp.open('GET', 'https://api.spotify.com/v1/search?q=Muse&type=track');
        xhttp.setRequestHeader('Content-Type', 'application/json');
        xhttp.setRequestHeader('Authorization', 'Bearer <MY_ACCESS_TOKEN>');
        xhttp.addEventListener('load', this.responseText);
        xhttp.send();*/
    },

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

        $.ajax({
            url: '/data/disconnect-qbo',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                M.toast({ html: '{Literal}QBO Successfully Disconnected{/Literal}' });
                location.reload();
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}An error has occured{/Literal}' });
                }
            }
        });
    },
});