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

@inject RunService RunService

@implements IDisposable

<div @onmouseover="@(() => _open = true)">
	<MudPopover Duration="100" OverflowBehavior="OverflowBehavior.FlipNever" Open="@_open" AnchorOrigin="Origin.TopRight" TransformOrigin="Origin.TopRight">
		<MudStack @onmouseleave="@(() => _open = false)" Justify="Justify.FlexEnd" Class="pa-0 ma-0" Spacing="0">
			<MudButton Disabled="true" Style="min-width: 20px; align-self: end">
				<MudIcon Icon="@Icons.Material.Filled.PlayArrow" Size="Size.Medium" Color="Color.Default"/>
			</MudButton>
			<MudList T="string" Dense="true" Class="pa-0 ma-0">
				@if (_ready)
				{
					@foreach (var project in RunnableProjects)
					{
						<MudListItem T="string" Dense="true" Class="pa-0 ma-0 pl-2" Style="max-height: 36px;">
							<MudStack Row="true" Spacing="1" AlignItems="AlignItems.Center" Class="pa-0 ma-0">
								<MudText>@project.Name</MudText>
								<MudSpacer/>
								@if (project.Running)
								{
									<MudButton Style="min-width: 20px;" OnClick="@(async () => await RunService.CancelRunningProject(project))">
										<MudIcon Icon="@Icons.Material.Filled.Stop" Size="Size.Medium" Color="Color.Error"/>
									</MudButton>
								}
								else
								{
									<MudButton Style="min-width: 20px;" OnClick="@(async () => await RunService.RunProject(project))">
										<MudIcon Icon="@Icons.Material.Filled.PlayArrow" Size="Size.Medium" Color="Color.Success"/>
									</MudButton>
								}
							</MudStack>
						</MudListItem>
					}
				}
			</MudList>
		</MudStack>
	</MudPopover>

	<MudButton Style="min-width: 20px;" >
		<MudIcon Icon="@Icons.Material.Filled.PlayArrow" Size="Size.Medium" Color="Color.Success"/>
	</MudButton>
</div>

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

	private IEnumerable<SharpIdeProjectModel> RunnableProjects => SolutionModel.AllProjects.Where(p => p.IsRunnable);

	private bool _open = false;
	private bool _ready = false;

	protected override void OnInitialized()
	{
		GlobalEvents.Instance.ProjectsRunningChanged.Subscribe(OnProjectsRunningChanged);
	}

	protected override async Task OnParametersSetAsync()
	{
		_ready = false;
		var tasks = SolutionModel.AllProjects.Select(p => p.MsBuildEvaluationProjectTask).ToList();
		await Task.WhenAll(tasks);
		_ready = true;
	}

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

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