import { BaseEditingController } from './base-editing.controller';
export class RowEditingController extends BaseEditingController {
    constructor(control, table) {
        super(control, table);
    }
    async onCreateStart() {
        this.table.activeRowIndex = 0;
        this.control.activeKey = undefined;
        this.control.createDisabled = true;
        return super.onCreateStart();
    }
    async onCreateEnd(event) {
        const valid = await this.validate(this.rowFromEvent(event.target));
        if (!valid) {
            return undefined;
        }
        this.control.createDisabled = false;
        this.table.activeRowIndex = undefined;
        return super.onCreateEnd(event);
    }
    async onDelete(event) {
        this.control.createDisabled = false;
        this.table.activeRowIndex = undefined;
        return super.onDelete(event);
    }
    onUpdateCancel() {
        this.control.createDisabled = false;
        this.table.activeRowIndex = undefined;
        if (!this.control.activeKey) {
            this.table.dispatchEvent(new CustomEvent('anjDelete', { detail: { index: 0, key: undefined } }));
        }
        else {
            this.control.activeKey = undefined;
        }
    }
    async onUpdateStart(event) {
        this.control.createDisabled = false;
        const removeAdd = this.table.activeRowIndex === 0 && !this.control.activeKey;
        const [index, data] = await super.onUpdateStart(event);
        this.table.activeRowIndex = removeAdd ? index - 1 : index;
        this.control.activeKey = event.detail.key;
        if (removeAdd) {
            this.table.dispatchEvent(new CustomEvent('anjDelete', { detail: { index: 0, key: undefined } }));
        }
        return [index, data];
    }
    async onUpdateEnd(event) {
        const valid = await this.validate(this.rowFromEvent(event.target));
        if (!valid) {
            return undefined;
        }
        const change = await super.onUpdateEnd(event);
        this.table.activeRowIndex = undefined;
        this.control.activeKey = undefined;
        return change;
    }
    // @ts-ignore
    async undo(change) {
        this.control.createDisabled = false;
        this.table.activeRowIndex = undefined;
    }
    async save() {
        return;
    }
    getEditType(data) {
        if (this.control.createDisabled && !data[this.table.rowKey]) {
            return 'create';
        }
        if (data[this.table.rowKey] && data[this.table.rowKey] === this.control.activeKey) {
            return 'update';
        }
        return undefined;
    }
    rowFromEvent(target) {
        return target.closest('tr');
    }
}
