/* global Bdf,$$ */
/**
 * Objet global définissant l'espace de nom TableDisplay
 * 
 * @namespace TableDisplay
 */
var TableDisplay = {};

TableDisplay.ARGS = {
    clientId: "",
    subsetKey: "",
    subsetCategory: "",
    subsetName: "",
    tableExportName: "",
    headerType: ""
};

TableDisplay.init = function (args) {
    var tableId = Bdf.generateId();
    var subsetKey = args.subsetKey;
    var subsetCategory = args.subsetCategory;
    var subsetName = args.subsetName;
    Bdf.Ajax.loadTable(args.tableExportName, subsetKey, function (table) {
        table = _completeTable(table);
        $$(args.clientId).html(Bdf.render("tabledisplay:table", table));
        $$(tableId).tablesorter({
            theme: "blue",
            textAttribute: "data-value",
            widgets: ['zebra']
        });
    });
    
    
    function _completeTable(table) {
        table.generatedId = tableId;
        table.withKeyHeader = (args.headerType === "columnkey");
        if (table.coldef.length === 0) {
            return table;
        }
        var withModifLink = false;
        var editUrl = "";
        var firstColName = table.coldef[0].name;
        if ((firstColName === "id") || (firstColName === "idcorpus") || (firstColName === "idths")) {
            withModifLink = true;
            if (subsetCategory === "corpus") {
                editUrl = "edition?page=fiche-change&corpus=" + subsetName + "&id=";
            } else if (subsetCategory === "thesaurus") {
                editUrl = "thesaurus?page=motcle-changeform&thesaurus=" + subsetName + "&id=";
            } else {
                withModifLink = false;
            }
        }
        table.editUrl = editUrl;
        for (let row of table.data) {
            for(let i = 0, len = row.length; i < len; i++) {
                let content = row[i];
                if ($.type(content) === "string") {
                    row[i] = {
                        isString: true,
                        text: content
                    };
                } else if (content.integer) {
                    if ((withModifLink) && (i === 0)) {
                        content.withLink = true;
                    }
                }
            }
        }
        return table;
    }

};


/******************************************************************************
 * Initialisation
 ******************************************************************************/

$(function () {
    Bdf.initTemplates();
    TableDisplay.init(TableDisplay.ARGS);
});
