/**
 * db-profiler.js
 *
 * @author Daniele De Nobili
 */

/*jslint nomen: true, plusplus: true, passfail: true, browser: true, devel: true */
/*global DBQueries */

(function (d, w) {
    'use strict';

    var panel, list, order = 'history';

    function render() {
        var code = '';

        DBQueries.forEach(function (query) {
            code += '<li><span>Query: ' + query.query + '</span><span>Values: ' + query.values + '</span><span>Time: ' + query.time + '</span></li>';
        });

        list.innerHTML = code;
    }

    function sortByTime() {
        if (order === 'delta') {
            return;
        }

        DBQueries.sort(function (a, b) {
            return b.time - a.time;
        });

        order = 'delta';

        render();
    }

    function sortByHistory() {
        if (order === 'history') {
            return;
        }

        DBQueries.sort(function (a, b) {
            return a.history - b.history;
        });

        order = 'history';

        render();
    }

    function attachEvents() {
        d.getElementById('pongho-db-profiler').addEventListener('click', function () {
            panel.classList.add('visible');
        });

        panel.getElementsByClassName('pongho-modal-overlay')[0].addEventListener('click', function () {
            panel.classList.remove('visible');
        });

        d.getElementById('sort-by-time').addEventListener('click', sortByTime);
        d.getElementById('sort-by-history').addEventListener('click', sortByHistory);
    }

    function onReady() {
        panel = d.getElementById('pongho-db-profiler-panel');
        list = panel.getElementsByTagName('ul')[0];

        attachEvents();
        render();
    }

    w.addEventListener('DOMContentLoaded', onReady);
}(document, window));
