import React from 'react';
import { enqueue, list, processQueue, clearDone, type QueueItem } from './queue';

export function useUploadQueue() {
  const [items, setItems] = React.useState<QueueItem[]>([]);
  const [loading, setLoading] = React.useState(true);

  const refresh = React.useCallback(async () => {
    setLoading(true);
    const all = await list();
    setItems(all);
    setLoading(false);
  }, []);

  const add = React.useCallback(async (it: Parameters<typeof enqueue>[0]) => {
    await enqueue(it);
    await refresh();
    await processQueue();
  }, [refresh]);

  const retryAll = React.useCallback(async () => {
    await processQueue();
    await refresh();
  }, [refresh]);

  const clearFinished = React.useCallback(async () => {
    await clearDone();
    await refresh();
  }, [refresh]);

  React.useEffect(() => {
    refresh();
    const online = () => processQueue().then(refresh);
    window.addEventListener('online', online);
    return () => window.removeEventListener('online', online);
  }, [refresh]);

  return { items, loading, refresh, add, retryAll, clearFinished } as const;
}

