var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
define(["require", "exports", "jquery", "./util", "./Excel"], function (require, exports, jquery_1, util_1, Excel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.appendRow = exports.getRowNum = exports.toggleEmptyState = void 0;
    jquery_1 = __importDefault(jquery_1);
    Excel_1 = __importDefault(Excel_1);
    function toggleEmptyState(container, show) {
        //console.log('toggleEmptyState', container, show);
        const emptyState = container === null || container === void 0 ? void 0 : container.querySelector('[data-md-table-empty]');
        if (emptyState) {
            emptyState.classList.toggle('d-none', !show);
        }
    }
    exports.toggleEmptyState = toggleEmptyState;
    function calcOrderColumn(table) {
        const list = table.querySelector('[data-md-table-list]');
        const row = list === null || list === void 0 ? void 0 : list.querySelectorAll('[data-md-table-row]');
        row === null || row === void 0 ? void 0 : row.forEach((element, index) => {
            const rowNum = element.querySelector('[data-md-table-row-num]');
            if (!rowNum) {
                throw '[data-md-table-row-num] is no defined';
            }
            rowNum.innerHTML = (index + 1) + '';
        });
        if (row == null || row.length === 0) {
            toggleEmptyState(table, true);
        }
    }
    function getRowNum(row) {
        var _a;
        //const index = Array.prototype.slice.call((row.parentElement as HTMLElement).children).indexOf(row);
        return Number((_a = row.querySelector('[data-md-table-row-num]')) === null || _a === void 0 ? void 0 : _a.innerHTML);
    }
    exports.getRowNum = getRowNum;
    function appendRow(table, changeFunc) {
        const rowTemplate = (0, util_1.getMDTarget)(table);
        const list = table.querySelector('[data-md-table-list]');
        if (!list) {
            throw '[data-md-table-list] is no defined';
        }
        (0, util_1.appendTemplate)(list, rowTemplate, changeFunc);
        toggleEmptyState(table, false);
        calcOrderColumn(table);
        table.dispatchEvent(new CustomEvent('add.md.table', {
            detail: {
                newNum: (0, jquery_1.default)(list).children().length
            }
        }));
    }
    exports.appendRow = appendRow;
    function Table(form, props) {
        (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-add"]', (ev) => {
            const tableSelector = (0, util_1.getMDTarget)(ev.currentTarget);
            const table = document.querySelector(tableSelector);
            if (!table) {
                throw 'table-add::table is no defined';
            }
            table.dispatchEvent(new Event('beforeAdd.md.table', { bubbles: true }));
        });
        (0, jquery_1.default)(form)[0].addEventListener('beforeAdd.md.table', (ev) => {
            appendRow(ev.target);
        });
        (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-remove"]', (ev) => {
            ev.preventDefault();
            const row = ev.currentTarget.closest('[data-md-table-row]');
            const rowNum = getRowNum(row);
            const container = row.closest('[data-md-table]');
            row.remove();
            calcOrderColumn(container);
            container.dispatchEvent(new CustomEvent('delete.md.table', {
                detail: {
                    oldNum: rowNum
                }
            }));
        });
        if (props && props.move) {
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-move-up"]', (ev) => {
                ev.preventDefault();
                const row = (0, jquery_1.default)(ev.currentTarget).closest('[data-md-table-row]');
                const container = row.closest('[data-md-table]');
                const rowPrev = row.prev();
                if (rowPrev.length > 0) {
                    rowPrev.before(row);
                    container[0].dispatchEvent(new CustomEvent('reorder.md.table', {
                        detail: {
                            oldNum: getRowNum(rowPrev[0]),
                            newNum: getRowNum(row[0])
                        }
                    }));
                }
                calcOrderColumn(container[0]);
            });
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-move-down"]', (ev) => {
                ev.preventDefault();
                const row = (0, jquery_1.default)(ev.currentTarget).closest('[data-md-table-row]');
                const container = row.closest('[data-md-table]');
                const rowNext = row.next();
                if (rowNext.length > 0) {
                    rowNext.after(row);
                    container[0].dispatchEvent(new CustomEvent('reorder.md.table', {
                        detail: {
                            old: getRowNum(rowNext[0]),
                            new: getRowNum(row[0])
                        }
                    }));
                }
                calcOrderColumn(container[0]);
            });
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-move-begin"]', (ev) => {
                ev.preventDefault();
                const row = (0, jquery_1.default)(ev.currentTarget).closest('[data-md-table-row]');
                const container = row.closest('[data-md-table]');
                const rowFirst = container.find('[data-md-table-row]').first();
                if (rowFirst.length > 0) {
                    rowFirst.before(row);
                    container[0].dispatchEvent(new CustomEvent('reorder.md.table', {
                        detail: {
                            old: getRowNum(rowFirst[0]),
                            new: getRowNum(row[0])
                        }
                    }));
                }
                calcOrderColumn(container[0]);
            });
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-move-end"]', (ev) => {
                ev.preventDefault();
                const row = (0, jquery_1.default)(ev.currentTarget).closest('[data-md-table-row]');
                const container = row.closest('[data-md-table]');
                const rowLast = container.find('[data-md-table-row]').last();
                if (rowLast.length > 0) {
                    rowLast.after(row);
                    container[0].dispatchEvent(new CustomEvent('reorder.md.table', {
                        detail: {
                            old: getRowNum(rowLast[0]),
                            new: getRowNum(row[0])
                        }
                    }));
                }
                calcOrderColumn(container[0]);
            });
        }
        if (props && props.copy) {
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-copy"]', (ev) => {
                ev.preventDefault();
                const row = ev.currentTarget.closest('[data-md-table-row]');
                const container = row.closest('[data-md-table]');
                container.dispatchEvent(new CustomEvent('beforeCopy.md.table', {
                    bubbles: true,
                    detail: {
                        row
                    }
                }));
            });
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-copy-current"]', (ev) => {
                ev.preventDefault();
                const container = document.querySelector((0, util_1.getMDTarget)(ev.currentTarget));
                const row = (0, jquery_1.default)(container).find('[data-md-table-row]:visible');
                container.dispatchEvent(new CustomEvent('beforeCopy.md.table', {
                    bubbles: true,
                    detail: {
                        row: row[0],
                        toEnd: true
                    }
                }));
            });
            (0, jquery_1.default)(form)[0].addEventListener('beforeCopy.md.table', (ev) => {
                var _a, _b;
                const detail = ev.detail;
                const row = detail.row;
                const container = row.closest('[data-md-table]');
                if (container) {
                    let newRow = row.cloneNode(true);
                    if (detail.toEnd) {
                        (_a = row.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(newRow);
                    }
                    else {
                        (_b = row.parentNode) === null || _b === void 0 ? void 0 : _b.insertBefore(newRow, row.nextSibling); // insertAfter
                    }
                    container.dispatchEvent(new CustomEvent('add.md.table', {
                        detail: {
                            newNum: getRowNum(newRow),
                            asCopy: getRowNum(row)
                        }
                    }));
                    calcOrderColumn(container);
                }
            });
        }
        if (props && props.excel) {
            (0, jquery_1.default)(form).on('click', '[data-md-toggle="table-excel"]', (ev) => {
                ev.preventDefault();
                const title = ev.currentTarget.getAttribute('title');
                const url = ev.currentTarget.getAttribute('data-md-url');
                Excel_1.default.create({
                    title,
                    url
                });
            });
        }
    }
    exports.default = Table;
    /*document.addEventListener("DOMContentLoaded", () => {
        $(document).on("click", "[data-md-toggle=\"table-add\"]", (ev) => {
            const container = $(getMDTarget(ev.currentTarget));
            if (container.length == 0) {
                throw "container is no defined";
            }
            container.trigger("append.md.table");
        });
    
        $('[data-md-table]').each(function() {
            Table
        })
    });*/
    // Polyfill - closest
    if (!Element.prototype.matches) {
        // @ts-ignore
        Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
    }
    if (!Element.prototype.closest) {
        Element.prototype.closest = function (s) {
            var el = this;
            do {
                if (Element.prototype.matches.call(el, s))
                    return el;
                // @ts-ignore
                el = el.parentElement || el.parentNode;
            } while (el !== null && el.nodeType === 1);
            return null;
        };
    }
});
