@using SharpIDE.Application.Features.Build

@inject BuildService BuildService

@implements IDisposable

<TerminalDisplay @ref="@_terminalDisplayRef"/>

@code {
	private TerminalDisplay _terminalDisplayRef = null!;

	protected override async Task OnInitializedAsync()
	{
		BuildService.BuildStarted += ClearPreviousOutput;
		_ = Task.Run(async () =>
		{
			try
			{
				await foreach (var logLine in BuildService.BuildTextWriter.ConsoleChannel.Reader.ReadAllAsync())
				{
					await _terminalDisplayRef.Write(logLine);
				}
			}
			catch (Exception e)
			{
				await DispatchExceptionAsync(e);
			}
		});
	}

	private async Task ClearPreviousOutput()
	{
		await _terminalDisplayRef.Clear();
		await InvokeAsync(StateHasChanged);
	}

	public void Dispose() => BuildService.BuildStarted -= ClearPreviousOutput;
}
