import { useEffect, useState } from 'react';

import { ipcChannels } from '../../../shared/ipc/contracts';
import type { AppToken } from '../../../shared/types';
import { getDndApi } from '../dndApi';

export function useAppTokens(): AppToken[] {
  const api = getDndApi();
  const [tokens, setTokens] = useState<AppToken[]>([]);

  useEffect(() => {
    void api.invoke(ipcChannels.tokens.list, {}).then(({ tokens: list }) => setTokens(list));
    return api.on(ipcChannels.tokens.stateChanged, ({ tokens: list }) => setTokens(list));
  }, [api]);

  return tokens;
}
