var Vtiger_ARDashboardLink_Js = {

    linkFetch: 'index.php?module=AdvancedReports&view=AdvancedReportsAjax&file=controller&a=getDashboardList',
    linkDashboard: 'index.php?module=AdvancedReports&view=Dashboard&dashboardId=',

    /**
     * Fast check for vTiger version
     */
    getVtigerVersion: function(view){
        if($("#navbar").length > 0) {
            return 7;
        }

        return 6;
    },

    /**
     * Check if string is JSON
     */
    isJsonString: function(string) {
        try {
            JSON.parse(string);
        } catch (e) {
            return false;
        }

        return true;
    },

    /**
     * Load dashboard list for vTiger 6
     */
    loadDashboardList6: function(view){
        var that = this;
        return AppConnector.request(this.linkFetch)
                    .then(function(result){
                        try {
                            console.log("loadDashboardList6", result);
                            return JSON.parse(result);
                        } catch(e) {
                            that.showErrorMessage(e.message);
                        }
                    })
    },

    /**
     * Load dashboard list for vTiger 7
     */
    loadDashboardList7: function(view){
        var that = this;
        return app.request.get({url: this.linkFetch})
            .then(function(error, result){
                try {
                    return JSON.parse(result);
                } catch(e) {
                    that.showErrorMessage(e.message);
                }
            })
    },

    /**
     * Show error message in dropdown menu
     * @param message
     */
    showErrorMessage: function(message) {
        // Remove all existing text
        $('#ardashboardhr').nextAll().remove();
        $("#ardashboardhr").after('<li style="text-align:center;">'+message+'</li>');
    },

    /**
     * Add dashboard link entries to dropdown menu
     * @param entries
     */
    addDashboardListEntries: function(entries) {
        var that = this;
        // Remove all existing links
        $('#ardashboardhr').nextAll().remove();

        if(entries.length == 0) {
            that.showErrorMessage("There are no dashboards to show");
        }

        // Add new links
        entries.map(function(dashboard) {
            // Create url
            var url =  that.linkDashboard + dashboard.id;
            $("#ardashboardhr").after('<li><a href="'+url+'">'+dashboard.title+'</a></li>');
        })
    },

    /**
     * Try to create dashboard list link entries into dropdown menu
     * 
     * This is called from addDashboardMenuIcon6 or addDashboardMenuIcon7()
     * function template onClick event
     */
    createDashboardList: function() {
        var that = this;
        var version = this.getVtigerVersion();
        if(version == 6) {
            var resource = this.loadDashboardList6();
        } else {
            var resource = this.loadDashboardList7();
        }

        resource
            .then(function(result) {
                console.log("createDashboardList", result);
                if(that.isJsonString(result)){
                    console.log("createDashboardList::that.isJsonString", result)
                    result = JSON.parse(result)
                }

                try {
                    if(result && result.dashboards) {
                        that.addDashboardListEntries(result.dashboards);
                    } else {
                        that.showErrorMessage("Unable to load dashboard list from server.");
                    }
                } catch(e) {
                    that.showErrorMessage(e.message);
                }
            })
    },

    /**
     * Add dashboard selection menu icon for vTiger 6
     */
    addDashboardMenuIcon6: function(view){
        var html = (function () {/*
        <span class="dropdown span settingsIcon">
            <a id="menubar_item_right_ardashboard" class="dropdown-toggle" data-toggle="dropdown" href="#"  onClick="Vtiger_ARDashboardLink_Js.createDashboardList();">
                <img src="layouts/vlayout/skins/softed/images/setting.png" alt="Advanced Reports Dashboards" title="Advanced Reports Dashboards" />
            </a>
            <ul class="dropdown-menu pull-right" style="width:500px;max-height:400px;overflow-y: scroll;">
                <div class="title" style="padding: 5px 0 0 15px;">
                    <strong>Advanced Report Dashboards</strong>
                </div>
                <hr id="ardashboardhr" />
            </ul>
        </span>
        */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

        $(".pull-right.headerLinksContainer:first").prepend(html);
    },

    /**
     * Add dashboard selection menu icon for vTiger 7
     */
    addDashboardMenuIcon7: function(view){
        var html = (function () {/*
        <li>
            <div class="dropdown">
                <div class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                    <a href="#" id="menubar_ARDashboards" class="qc-button fa fa-tachometer" title="Advanced Report Dashboards" aria-hidden="true" onClick="Vtiger_ARDashboardLink_Js.createDashboardList();"></a>
                </div>
                <ul class="dropdown-menu" role="menu" aria-labelledby="ar-dashboards" style="width:500px;max-height:400px;overflow-y: scroll;">
                    <li class="title" style="padding: 5px 0 0 15px;">
                        <strong>Advanced Report Dashboards</strong>
                    </li>
                    <hr id="ardashboardhr" />
                </ul>
            </div>
        </li>
        */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

        $("#navbar").find("ul:first").prepend(html);
    },

    /**
     * Function to register required events
     */
    registerEvents : function(){
        // Add correct link for right version
        var version = this.getVtigerVersion();
        if(version == 6) {
            this.addDashboardMenuIcon6();
        } else {
            this.addDashboardMenuIcon7();
        }
    }
}

// On Page Load
jQuery(window).load(function() {
    Vtiger_ARDashboardLink_Js.registerEvents();
});