using AzureAi.Transcriber.Services;
using Microsoft.AspNetCore.Components;

namespace AzureAi.Transcriber.Components.Pages;

public class HomeBase: ComponentBase
{
    [Inject]
    protected ILogger<HomeBase> Logger { get; set; } = null!;
    
    [Inject]
    protected IFileService FileService { get; set; } = null!;
    
    [Inject]
    protected ITranscribeService TranscribeService { get; set; } = null!;
    
    public List<string> Files { get; set; } = [];
    public string? SelectedFile { get; set; }
    
    public bool TranscribeInProgress { get; set; }

    public string Transcription { get; set; } = string.Empty;
    
    protected override async Task OnInitializedAsync()
    {
        Files = await FileService.GetFiles();
    }

    protected void SelectFile(string path)
    {
        if (path == SelectedFile)
        {
            SelectedFile = string.Empty;
            InvokeAsync(StateHasChanged);
            return;
        }
        
        if (TranscribeInProgress)
        {
            Logger.LogWarning("Transcription in progress, cannot select new file.");
            return;
        }
        
        Logger.LogInformation("Selected file: {path}", path);
        SelectedFile = path;
        InvokeAsync(StateHasChanged);
    }

    protected async void Transcribe(bool full = false)
    {
        if (string.IsNullOrWhiteSpace(SelectedFile))
        {
            Logger.LogWarning("No file selected for transcription.");
            return;
        }
        
        try
        {
            Logger.LogInformation("Beginning transcription of: {path}", SelectedFile);
            
            TranscribeInProgress = true;
            Transcription = string.Empty;
            await InvokeAsync(StateHasChanged);

            Transcription = full
                ? await TranscribeService.TranscribeFull(SelectedFile)
                : await TranscribeService.TranscribeSnippet(SelectedFile);
            
            Logger.LogInformation("Transcription complete for: {path}", SelectedFile);
        }
        catch (Exception e)
        {
            Logger.LogError(e, "Failed to transcribe {path}", SelectedFile);
            // Todo: display error
        }
        
        TranscribeInProgress = false;
        await InvokeAsync(StateHasChanged);
    }
}