import { UmbStoreAppendEvent, UmbStoreRemoveEvent, UmbStoreUpdateEvent } from './events/index.js';
import { UmbContextConsumerController } from '../../../libs/context-api/index.js';
// WIP: get back to this when we have decided on detail model sizes
export class UmbStoreConnector {
    #store;
    #connectedStore;
    #newStoreItemMapper;
    #updateStoreItemMapper;
    constructor(host, args) {
        this.#store = args.store;
        this.#newStoreItemMapper = args.newStoreItemMapper;
        this.#updateStoreItemMapper = args.updateStoreItemMapper;
        new UmbContextConsumerController(host, args.connectToStoreAlias, (instance) => {
            this.#connectedStore = instance;
            if (this.#connectedStore) {
                this.#listenToConnectedStore();
            }
        });
    }
    #listenToConnectedStore = () => {
        if (!this.#connectedStore)
            return;
        this.#connectedStore.addEventListener(UmbStoreAppendEvent.TYPE, this.#updateStoreItems);
        this.#connectedStore.addEventListener(UmbStoreUpdateEvent.TYPE, this.#updateStoreItems);
        this.#connectedStore.addEventListener(UmbStoreRemoveEvent.TYPE, this.#removeStoreItems);
    };
    #updateStoreItems = (event) => {
        event.uniques.forEach((unique) => {
            const storeHasItem = this.#store.getItems([unique]).length > 0;
            const connectedStoreItem = this.#connectedStore.getItems([unique])[0];
            // we check if the current store has the item from the connected store, if it does we update it, if it doesn't we append it
            if (storeHasItem && this.#updateStoreItemMapper) {
                this.#store.updateItem(unique, this.#updateStoreItemMapper(connectedStoreItem));
            }
            else if (this.#newStoreItemMapper) {
                this.#store.append(this.#newStoreItemMapper(connectedStoreItem));
            }
        });
    };
    #removeStoreItems = (event) => {
        this.#store.removeItems(event.uniques);
    };
}
