@using SharpIDE.Application.Features.Events
@using SharpIDE.Application.Features.Run
@using SharpIDE.Application.Features.SolutionDiscovery.VsPersistence

@implements IDisposable

@inject RunService RunService

<MudStack Style="height: 100%">
	<style>
		.lowercase-tab-header {
			text-transform: none;
		}
		.panels-full-height {
			height: 100%;
		}
	</style>
	@* <MudText>Run</MudText> *@
	<MudTabs @ref="_mudTabsRef" Style="height: 100%" KeepPanelsAlive="true" PanelClass="panels-full-height" TabPanelClass="lowercase-tab-header">
		<ChildContent>
			@foreach (var tab in OpenTabs)
			{
				<MudTabPanel Style="height: 100%" ID="@tab" Text="@tab.Name">
					<RunOutputDisplay Project="@tab" OnProjectStarted="@SetActiveTab"/>
				</MudTabPanel>
			}
		</ChildContent>
		<TabPanelHeader>
			@if (context.ID is SharpIdeProjectModel project)
			{
				@if (project.Running)
				{
					<MudIcon Icon="@Icons.Material.Filled.Circle" Class="pa-1" Size="Size.Small" Color="Color.Success"/>
				}
				else
				{
					<MudIconButton Color="Color.Inherit" Class="pa-0" Size="Size.Small" Icon="@Icons.Material.Filled.Close" OnClick="@(() => CloseTab(project))"/>
				}
			}
			else throw new InvalidOperationException("Tab ID must be of type SharpIdeProjectModel");
		</TabPanelHeader>
	</MudTabs>
</MudStack>

@code {
	[Parameter, EditorRequired]
	public SharpIdeSolutionModel SolutionModel { get; set; } = null!;

	private MudTabs _mudTabsRef = null!;

	private IEnumerable<SharpIdeProjectModel> OpenTabs => SolutionModel.AllProjects.Where(s => s.OpenInRunPanel);

	protected override async Task OnInitializedAsync()
	{
		var tasks = SolutionModel.AllProjects.Select(p => p.MsBuildEvaluationProjectTask);
		await Task.WhenAll(tasks);
		GlobalEvents.Instance.ProjectsRunningChanged.Subscribe(OnProjectsRunningChanged);
	}

	private void CloseTab(SharpIdeProjectModel project)
	{
		project.OpenInRunPanel = false;
	}

	private async Task OnProjectsRunningChanged()
	{
		await InvokeAsync(StateHasChanged);
	}

	public void Dispose() => GlobalEvents.Instance.ProjectsRunningChanged.Unsubscribe(OnProjectsRunningChanged);

	private void SetActiveTab(SharpIdeProjectModel project)
	{
		_mudTabsRef.ActivatePanel(project);
	}
}
