import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { createTransactionTaskId } from '../util/transactionTask.js';
export const useTransactionTaskStore = create(immer(set => ({
    taskEntryById: {},
    createTask: (task) => {
        set(state => {
            const id = createTransactionTaskId(task);
            state.taskEntryById[id] = {
                id,
                request: task,
                createdAt: new Date(),
            };
        });
    },
    completeTask: (id, result) => {
        set(state => {
            if (state.taskEntryById[id]) {
                state.taskEntryById[id].result = result;
            }
        });
    },
})));
const taskListener = {};
const alertListener = (id, result) => {
    const listener = taskListener[id];
    delete taskListener[id];
    if (listener) {
        listener(result);
    }
};
export const requestTransactionTask = async (task) => {
    return new Promise((resolve, reject) => {
        const id = createTransactionTaskId(task);
        useTransactionTaskStore.getState().createTask(task);
        taskListener[id] = (result) => {
            if (result.type === 'success') {
                resolve(result.hash);
            }
            else {
                reject(result.error);
            }
        };
    });
};
export const onNewTask = (task) => {
    useTransactionTaskStore.getState().createTask(task);
};
export const onTaskSuccess = (id, hash) => {
    const result = { type: 'success', hash };
    useTransactionTaskStore.getState().completeTask(id, result);
    alertListener(id, result);
};
export const onTaskError = (id, error) => {
    const result = { type: 'error', error };
    useTransactionTaskStore.getState().completeTask(id, result);
    alertListener(id, result);
};
