import { KeyValuePipe } from '@angular/common';
import { Component, inject, input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { Api } from '../../api/api';
import { previewStatus } from '../../api/fn/preview/preview-status';
import { startPreview } from '../../api/fn/preview/start-preview';
import type { PreviewResult } from '../../api/models/preview-result';
import type { Run } from '../../api/models/run';
import { RunMonitor, errorText } from '../run-monitor';
import { downloadPreviewPdf } from './preview-pdf';
@Component({
selector: 'app-eeg-preview',
imports: [
FormsModule,
KeyValuePipe,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
RunMonitor,
],
template: `
@if (error()) {
{{ error() }}
}
@if (runId(); as id) {
}
`,
})
export class EegPreview {
readonly active = input.required();
private readonly api = inject(Api);
protected readonly edfFiles = signal(null);
protected readonly adosFiles = signal(null);
protected readonly busy = signal(false);
protected readonly error = signal('');
protected readonly runId = signal('');
protected readonly result = signal(null);
protected readonly unsorted = () => 0;
protected readonly exporting = signal(false);
protected readonly pdfError = signal('');
protected async pdf(result: PreviewResult): Promise {
this.exporting.set(true);
this.pdfError.set('');
try {
await downloadPreviewPdf(result);
} catch (error) {
this.pdfError.set(errorText(error));
} finally {
this.exporting.set(false);
}
}
protected async start(edf?: File, ados2?: File, birth_date?: string): Promise {
if (!edf) return;
this.busy.set(true);
this.error.set('');
this.result.set(null);
try {
const { run_id } = await this.api.invoke(startPreview, {
body: { edf, ados2, birth_date: birth_date || undefined },
});
this.runId.set(run_id);
} catch (error) {
this.error.set(errorText(error));
this.busy.set(false);
}
}
protected async finish(run: Run, dialog: HTMLDialogElement): Promise {
try {
if (run.state !== 'succeeded') return;
const { result } = await this.api.invoke(previewStatus, { run_id: run.id });
this.result.set(result);
if (result) dialog.showModal();
else this.error.set('La vista previa no devolvió un resultado.');
} catch (error) {
this.error.set(errorText(error));
} finally {
this.busy.set(false);
}
}
}