/* global Bdf,$$,Intl */
/**
 * Objet global définissant l'espace de nom TableSheet
 * 
 * @namespace TableSheet
 */
TableSheet = function(fapi, tableId, subsetCategory, subsetName, columnArray, cellFactory, cssResolver, settings) {
    this.fapi = fapi;
    this.tableId = tableId;
    this.subsetCategory = subsetCategory;
    this.subsetName = subsetName;
    this.cellFactory = cellFactory;
    this.columnArray = columnArray;
    this.rowArray = [];
    this.rowMap = new Map();
    this.cssResolver = cssResolver;
    this.withSum = false;
    this.settings = Object.assign({
        forceEditable: false,
        tbodyId: tableId + "_tbody",
        tfootId: tableId + "_tfoot",
        viewportId: tableId + "_viewport",
        odSheetname: subsetName,
        odFixedRows: 1,
        odFixedColumns: 1
    }, settings);
};

TableSheet.prototype.convertToRow = function (dataEntry) {
    var editable = dataEntry.editable;
    if (this.settings.forceEditable) {
        editable = true;
    }
    var row = new TableSheet.Row(this, dataEntry.id, editable);
    this.updateCells(row, dataEntry.properties);
    this.rowArray.push(row);
    this.rowMap.set(row.subsetItemId, row);
    return row;
};

TableSheet.prototype.getRow = function (id) {
    return this.rowMap.get(id.toString());
};

TableSheet.prototype.updateCells = function (row, properties) {
    let cellFactory = this.cellFactory;
    let originalCellArray = row.originalCellArray;
    let array = [];
    for(let column of this.columnArray) {
        let name = column.name;
        let cell;
        if (properties.hasOwnProperty(name)) {
            cell = cellFactory.buildCell(properties[name], column.context);
        } else {
            cell = new TableSheet.Cell("");
        }
        if (column.variant) {
            switch(column.variant) {
                case "edit":
                    if ((this.subsetCategory === "corpus") && (row.editable)) {
                        cell.setCustomTemplate("tablesheet:cell_ficheedit", {
                            ficheId: row.subsetItemId
                        });
                    }
                    break;
            }
        }
        if (column.match) {
            cell.setData("goto", column.match);
        }
        if (originalCellArray) {
            let originalCell = originalCellArray[column.index];
            if (cell.text !== originalCell.text) {
                cell.addClass("tablesheet-Change");
            }
        }
        array.push(cell);
    }
    if (!originalCellArray) {
        row.originalCellArray = array;
    }
    row.currentCellArray = array;
};

TableSheet.prototype.addRowToExisting = function (data) {
    var tableSheet = this;
    var row = tableSheet.convertToRow(data);
    var $table = $$(tableSheet.tableId);
    $$(tableSheet.settings.tbodyId).append($(Bdf.render("tablesheet:row", row)));
    $table.trigger('addRows', [$(row.getMatchingTrElement()), false]);
    $$(tableSheet.settings.viewportId).animate({
        scrollTop: $table.height()
    }, 1000);
    tableSheet.updateCounter();
    return row;
};


TableSheet.prototype.initTableSorter = function () {
    $$(this.tableId).tablesorter({
        theme: "blue",
        textAttribute: "data-value",
        widgets: ["zebra", "filter"],
        ignoreCase: true,
        sortLocaleCompare : true,
        emptyTo: "emptyMin"
    });
};

TableSheet.prototype.initActions = function (settings) {
    settings = Object.assign({
        editOnAction: true,
        editOnDblclik: true,
        hideFootOnFilter: true
    }, settings);
    var tableSheet = this;
    var $table = $$(tableSheet.tableId);
    if (settings.editOnAction) {
        $table.on("click", $$.toCssSelector({action: "ficheedit"}), function () {
            let row = tableSheet.getRow(this.dataset.ficheId);
            tableSheet.editFiche(row);
            return false;
        });
    }
    if (settings.editOnDblclik) {
        $table.on("dblclick", "td", function (event) {
            if ((!event.altKey) && (!event.shiftKey) && (!event.crtlKey) && (!event.metaKey)) {
                let cell = this;
                let row = tableSheet.getRow(cell.parentElement.dataset.subsetItemId);
                tableSheet.editFiche(row, cell);
            }
        });
    }
    if (settings.hideFootOnFilter) {
        $table.bind('filterEnd', function(e, filter) {
            let filteredCount = $$(tableSheet.settings.tbodyId).find("tr.filtered").length;
            let tfootElement = $$.first(tableSheet.settings.tfootId);
            if (tfootElement) {
                if (filteredCount > 0) {
                    tfootElement.classList.add("hidden");
                } else {
                    tfootElement.classList.remove("hidden");
                }
            }
            tableSheet.updateCounter();
        });
    }
};

TableSheet.prototype.updateCounter = function () {
    var tableSheet = this;
    let allCount = tableSheet.rowArray.length;
    let remainingCount = allCount - $$(tableSheet.settings.tbodyId).find("tr.filtered").length;
    allCount = allCount.toString();
    remainingCount = remainingCount.toString();   
    let diff = allCount.length - remainingCount.length;
    if (diff > 0) {
        for(let i = 0; i < diff; i++) {
            remainingCount = "&nbsp;" + remainingCount;
        }
    }
    $$(tableSheet.tableId, "count", "filter").html(remainingCount);
    $$(tableSheet.tableId, "count", "all").html(allCount);    
};

TableSheet.prototype.editFiche = function (row, tdElement) {
    if (!row) {
        return;
    }
    if (!row.editable) {
        return;
    }
    var tableSheet = this;
    if (tableSheet.subsetCategory !== "corpus") {
        return;
    }
    var corpus = tableSheet.subsetName;  
    var trElement = row.getMatchingTrElement();
    trElement.classList.add("tablesheet-Active");
    var extraParameters = {};
    if ((tdElement) && (tdElement.dataset.goto)) {
        extraParameters.goto = tdElement.dataset.goto;
    }
    Bdf.Overlay.showFicheEditor(corpus, row.subsetItemId, {
        doneCallback: _doneCalback,
        cancelCallback: _cancelCallback,
        extraParameters: extraParameters
    });
    
    function _doneCalback(corpus, id) {
        tableSheet.fapi.loadFiche({
            corpus: corpus,
            id: id,
            callback: function (data) {
                tableSheet.updateCells(row, data.fiche.properties);
                setTimeout(function () {
                    $(trElement).html(Bdf.render("tablesheet:cellarray", row));
                    trElement.classList.remove("tablesheet-Active");
                    $$(tableSheet.tableId).trigger('update', [true]);
                }, 500);
           }
       });
    }
                
    function _cancelCallback() {
        setTimeout(function () {
            trElement.classList.remove("tablesheet-Active");
        }, 500);
    }
};
