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

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

TableSheet.init = function (args) {
    Bdf.Api.init();
    var tableId = Bdf.generateId();
    var subsetKey = args.subsetKey;
    var subsetCategory = args.subsetCategory;
    var subsetName = args.subsetName;
    var table, tableMeta;
    var engine, rowMap;
    Bdf.Ajax.loadTable(args.tableExportName, subsetKey, function (tableObj) {
        table = tableObj;
        tableMeta = tableObj.meta;
        _completeTable();
        $$(args.clientId).html(Bdf.render("tablesheet:table", table));
        $$(tableId).tablesorter({
            theme: "blue",
            textAttribute: "data-value",
            widgets: ["zebra", "filter"],
            ignoreCase: true,
            sortLocaleCompare : true,
            emptyTo: "emptyMin"
        }).on("click", $$.toCssSelector({action: "edit"}), function () {
            if (subsetCategory === "corpus") {
                let id = this.dataset.id;
                _editFiche(subsetName, id);
            }
            return false;
        }).on("dblclick", "td", function (event) {
            if ((!event.altKey) && (!event.shiftKey) && (!event.crtlKey) && (!event.metaKey)) {
                let cell = this;
                let row = cell.parentElement;
                if (row.dataset.editable) {
                    _editFiche(subsetName, row.dataset.id, cell);
                }
            }
        });
    });
    
    function _editFiche(corpus, id, td) {
        let row = $$({_element:"tr", id: id})[0];
        row.classList.add("tablesheet-Active");
        let extraParameters = {};
        if ((td) && (td.dataset.goto)) {
            extraParameters.goto = td.dataset.goto;
        }
        Bdf.Overlay.showFicheEditor(corpus, id, {
            doneCallback: __doneCalback,
            cancelCallback: __cancelCallback,
            extraParameters: extraParameters
        });
        
        function __doneCalback(corpus, id) {
            Bdf.api.loadFiche({
                corpus: corpus,
                id: id,
                requestParameters: {
                    properties: tableMeta.mapping
                },
                callback: function (data) {
                    let cellArray = _toCellArray(id, data.fiche.properties, _getOriginalCellArray(data.fiche.id));
                    setTimeout(function () {
                        $(row).html(Bdf.render("bdf:cell", cellArray));
                        row.classList.remove("tablesheet-Active");
                    }, 500);

               }
           });
        }
                
        function __cancelCallback() {
            setTimeout(function () {
                row.classList.remove("tablesheet-Active");
            }, 500);
        }
    }
    
    function _completeTable() {
        table.generatedId = tableId;
        table.withKeyHeader = (args.headerType === "columnkey");
        if (table.meta.columns.length === 0) {
            return table;
        }
        for(let column of table.meta.columns) {
            let name = column.name;
            switch(name) {
                case "id":
                case "idcorpus":
                case "idths":
                    column.action = "edit";
            }
            column.context = {};
            if (column.datestyle) {
                column.context.dateFormatter = new Bdf.Cell.DateFormatter(table.meta.locale, column.datestyle);
            } else if (column.cast === "date") {
                column.context.dateFormatter = new Bdf.Cell.DateFormatter(table.meta.locale, "medium");
            }
        }
        table.rows = [];
        rowMap = new Map();
        engine = new Bdf.Cell.Engine({
            lang: table.meta.lang
            
        });       
        
        for (let entry of table.data) {
            let cellArray = _toCellArray(entry.id, entry.properties);
            let row = {id: entry.id, editable: entry.editable, cells: cellArray};
            table.rows.push(row);
            rowMap.set(entry.id.toString(), row);
        }
        return table;
    }
    
    function _getOriginalCellArray(id) {
        let row = rowMap.get(id.toString());
        if (!row) {
            return null;
        }
        return row.cells;
    }
    
    function _toCellArray(id, properties, originalCellArray) {
        let array = [];
        let columnIndex = 0;
        for(let column of tableMeta.columns) {
            let name = column.name;
            let cell;
            if (properties.hasOwnProperty(name)) {
                cell = engine.convert(properties[name], column.context);
            } else {
                cell = new Bdf.Cell("");
            }
            if (column.action) {
                cell.setLinkData("action", column.action);
                cell.setLinkData("id", id);
            }
            if (column.match) {
                cell.setData("goto", column.match);
            }
            if (originalCellArray) {
                let originalCell = originalCellArray[columnIndex];
                if (cell.text !== originalCell.text) {
                    cell.addClass("tablesheet-Change");
                }
            }
            array.push(cell);
            columnIndex++;
        }
        return array;
    }

};


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

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