const CONTROL_SELECTOR = 'anj-input, anj-checkbox, anj-select';
export class BaseEditingController {
    constructor(control, table) {
        this.control = control;
        this.table = table;
    }
    static isDirty(data, row) {
        let dirty = false;
        for (const prop in data) {
            if (data[prop] !== row[prop]) {
                dirty = true;
                break;
            }
        }
        return dirty;
    }
    async onCreateStart() {
        const data = {};
        const columns = await this.table.getColumns();
        columns.forEach(c => {
            data[c.field] = typeof c.defaultValue === 'function' ? c.defaultValue(c) : c.defaultValue;
        });
        return data;
    }
    async onCreateEnd({ target }) {
        return this.getData(target);
    }
    async onDelete({ target }) {
        const rows = await this.table.getRows();
        const index = this.indexByElement(target);
        return [rows[index], index];
    }
    async onUpdateStart(event) {
        const rows = await this.table.getRows();
        const index = this.indexByElement(event.target);
        return [index, rows[index]];
    }
    async onUpdateEnd({ target }) {
        const rows = await this.table.getRows();
        const index = this.indexByElement(target);
        const row = rows[index];
        const data = this.getData(target);
        return BaseEditingController.isDirty(data, row) ? [data, row, index] : undefined;
    }
    onUpdateCancel() { }
    async validate(el) {
        if (!el)
            return;
        const results = await Promise.all(Array.from(el.querySelectorAll(CONTROL_SELECTOR)).map(async (e) => e.checkValidity()));
        // Find any validity check where the value is false, if there are none, then it is valid
        return (results.find(i => !i) !== false);
    }
    getData(target) {
        const controls = target.closest('tr').querySelectorAll(CONTROL_SELECTOR);
        const data = {};
        controls.forEach(c => {
            if (c.tagName === 'ANJ-CHECKBOX') {
                const control = c;
                data[control.name] = control.checked;
            }
            else {
                const control = c;
                data[control.name] = control.value;
            }
        });
        return data;
    }
    indexByElement(target) {
        return Array.from(this.table.querySelectorAll('anj-row-edit-control')).findIndex(el => el === target);
    }
}
