import { UmbEntityBulkActionBase } from '../../entity-bulk-action-base.js';
import { createExtensionApiByAlias } from '../../../extension-registry/index.js';
import { umbConfirmModal } from '../../../modal/index.js';
import { UMB_ACTION_EVENT_CONTEXT } from '../../../action/index.js';
import { UmbEntityDeletedEvent, UmbRequestReloadChildrenOfEntityEvent, UmbRequestReloadStructureForEntityEvent, } from '../../../entity-action/index.js';
import { UMB_NOTIFICATION_CONTEXT } from '../../../notification/index.js';
import { UmbLocalizationController } from '../../../../../libs/localization-api/index.js';
import { UMB_ENTITY_CONTEXT } from '../../../entity/index.js';
export class UmbDeleteEntityBulkAction extends UmbEntityBulkActionBase {
    #localize = new UmbLocalizationController(this);
    #items = [];
    /**
     * @deprecated this has been turned into a private property and cannot be used from v.18. Will be removed in v.18
     */
    get _items() {
        return this.#items;
    }
    /**
     * @deprecated this has been turned into a private property and cannot be used from v.18. Will be removed in v.18
     */
    set _items(value) {
        this.#items = value;
    }
    async execute() {
        if (this.selection?.length === 0) {
            throw new Error('No items selected.');
        }
        // TODO: Move item look up to a future bulk action context
        await this.#requestItems();
        await this._confirmDelete(this.#items);
        await this.#requestBulkDelete(this.selection);
    }
    async _confirmDelete(items) {
        const headline = '#actions_delete';
        const message = '#defaultdialogs_confirmBulkDelete';
        // TODO: consider showing more details about the items being deleted
        await umbConfirmModal(this._host, {
            headline,
            content: this.#localize.string(message, items.length),
            color: 'danger',
            confirmLabel: '#actions_delete',
        });
    }
    async #requestItems() {
        const itemRepository = await createExtensionApiByAlias(this, this.args.meta.itemRepositoryAlias);
        const { data } = await itemRepository.requestItems(this.selection);
        this.#items = data ?? [];
    }
    async #requestBulkDelete(uniques) {
        const detailRepository = await createExtensionApiByAlias(this, this.args.meta.detailRepositoryAlias);
        const notificationContext = await this.getContext(UMB_NOTIFICATION_CONTEXT);
        const succeeded = [];
        for (const unique of uniques) {
            const { error } = await detailRepository.delete(unique);
            if (error) {
                const notification = { data: { message: error.message } };
                notificationContext?.peek('danger', notification);
            }
            else {
                succeeded.push(unique);
            }
        }
        if (succeeded.length > 0) {
            const notification = {
                data: { message: `Deleted ${succeeded.length} ${succeeded.length === 1 ? 'item' : 'items'}` },
            };
            notificationContext?.peek('positive', notification);
        }
        await this.#notify(succeeded);
    }
    async #notify(succeeded) {
        const entityContext = await this.getContext(UMB_ENTITY_CONTEXT);
        if (!entityContext)
            throw new Error('Entity Context is not available');
        const eventContext = await this.getContext(UMB_ACTION_EVENT_CONTEXT);
        if (!eventContext)
            throw new Error('Event Context is not available');
        const entityType = entityContext.getEntityType();
        const unique = entityContext.getUnique();
        if (entityType && unique !== undefined) {
            const args = { entityType, unique };
            const reloadChildren = new UmbRequestReloadChildrenOfEntityEvent(args);
            eventContext.dispatchEvent(reloadChildren);
            const reloadStructure = new UmbRequestReloadStructureForEntityEvent(args);
            eventContext.dispatchEvent(reloadStructure);
        }
        const succeededItems = this.#items.filter((item) => succeeded.includes(item.unique));
        succeededItems.forEach((item) => {
            const deletedEvent = new UmbEntityDeletedEvent({
                unique: item.unique,
                entityType: item.entityType,
            });
            eventContext.dispatchEvent(deletedEvent);
        });
    }
}
export { UmbDeleteEntityBulkAction as api };
