import { useQuery } from '@tanstack/react-query'; import { getHomeUsers, switchHomeUser } from '../plex/account'; import type { HomeUser } from '../plex/types'; import { promptDialog, toastError } from '../ui/overlays'; import { useSession } from './session'; import { queryClient } from './queries'; /** Plex Home profiles available to the signed-in account. */ export function useHomeUsers() { const token = useSession((s) => s.accountToken); const home = useSession((s) => s.user?.home); const { data } = useQuery({ queryKey: ['homeUsers', token], queryFn: () => getHomeUsers(token!), enabled: !!token && !!home, staleTime: 10 * 60_000, }); return { users: data ?? [], async switchTo(u: HomeUser) { try { let pin: string | undefined; if (u.protected) { const v = await promptDialog({ title: `Switch to ${u.title}`, message: 'This profile is protected by a PIN.', confirm: 'Switch', input: { label: 'PIN', type: 'password', placeholder: '4-digit PIN' }, }); if (v === null) return; pin = v; } const next = await switchHomeUser(token!, u.uuid, pin); queryClient.clear(); await useSession.getState().switchUser(next); } catch (e) { toastError(e); } }, }; }