import { BaseEditingController } from './base-editing.controller';
export class BatchEditingController extends BaseEditingController {
    constructor(control, table) {
        super(control, table);
        this.deleteKeys = [];
        this.updateKeys = [];
    }
    // @ts-ignore
    getEditType(data) {
        return undefined;
    }
    async onUpdateEnd(event) {
        const change = await super.onUpdateEnd(event);
        if (change) {
            this.updateKeys.push(event.detail.key);
        }
        return change;
    }
    async onDelete(event) {
        const change = await super.onDelete(event);
        if (change[0][this.table.rowKey]) {
            this.deleteKeys.push(change[0][this.table.rowKey]);
        }
        return change;
    }
    async undo(change) {
        const rows = await this.table.getRows();
        let data;
        let key;
        let index;
        if (change.create) {
            data = change.create[0];
            key = data[this.table.rowKey];
            this.deleteKeys = this.deleteKeys.filter(k => k !== key);
            this.table.dispatchEvent(new CustomEvent('anjCreateStart', { detail: { key, data } }));
        }
        else if (change.update) {
            data = change.update[0];
            key = data[this.table.rowKey];
            index = rows.findIndex(r => r[this.table.rowKey] === key);
            const keyIndex = this.updateKeys.findIndex(k => k === change.update[0][this.table.rowKey]);
            this.updateKeys.splice(keyIndex, 1);
            this.table.dispatchEvent(new CustomEvent('anjUpdateEnd', { detail: { key, data, index } }));
        }
        else {
            data = change.delete[0];
            key = data[this.table.rowKey];
            index = rows.findIndex(r => r[this.table.rowKey] === key);
            this.table.dispatchEvent(new CustomEvent('anjDelete', { detail: { key, data, index } }));
        }
    }
    async save() {
        const valid = await this.validate(this.table.querySelector('table'));
        if (!valid) {
            return undefined;
        }
        const rows = await this.table.getRows();
        const creates = rows.filter(r => !r[this.table.rowKey]);
        const change = {};
        if (creates.length > 0) {
            change.create = creates;
        }
        if (this.deleteKeys.length > 0) {
            change.delete = this.deleteKeys;
        }
        if (this.updateKeys.length > 0) {
            change.update = rows.filter(r => (r[this.table.rowKey] && this.updateKeys.includes(r[this.table.rowKey])));
        }
        return change;
    }
}
