import { useState } from 'react' import { checkFile, uploadDrawing, type Candidate, type Step, type UploadError, } from './drawingUpload' import type { RepairOffer } from './repair' export type UploadUi = | { phase: 'idle' } | { phase: 'working' } | { phase: 'cleaning'; candidate: Candidate } | { phase: 'repair'; offer: RepairOffer } | { phase: 'failed'; error: UploadError } | { phase: 'done' } export interface DrawingUpload { ui: UploadUi /** A picked file: checked, then sent (clean) or offered for cleaning (cleanable). */ start: (file: File) => Promise /** « Nettoyer et utiliser cette version ». */ confirmCleaning: () => Promise cancelCleaning: () => void /** The repair dialog applied: the drawing is attached with the repaired annotations. */ finishRepair: () => void /** « Annuler »: the document stays as it is, the drawing stays uploaded and held. */ cancelRepair: () => void } /** The upload of one view's drawing as a small state machine for its section. */ export function useDrawingUpload(viewId: string): DrawingUpload { const [ui, setUi] = useState({ phase: 'idle' }) const settle = (result: Step) => { if (result.ok) setUi({ phase: 'done' }) else if (result.error.code === 'stale') setUi({ phase: 'idle' }) else if (result.error.code === 'repair') setUi({ phase: 'repair', offer: result.error.offer }) else setUi({ phase: 'failed', error: result.error }) } const send = async (candidate: Candidate) => { setUi({ phase: 'working' }) settle(await uploadDrawing(candidate, viewId)) } const start = async (file: File) => { setUi({ phase: 'working' }) const checked = await checkFile(file) if (!checked.ok) return settle(checked) if (checked.value.outcome === 'clean') return send(checked.value) setUi({ phase: 'cleaning', candidate: checked.value }) } return { ui, start, confirmCleaning: async () => { if (ui.phase === 'cleaning') await send(ui.candidate) }, cancelCleaning: () => setUi({ phase: 'idle' }), finishRepair: () => setUi({ phase: 'done' }), cancelRepair: () => { if (ui.phase !== 'repair') return const { refusal } = ui.offer setUi({ phase: 'failed', error: { code: 'frame', refusal } }) }, } }