using Connected.Annotations;
using Connected.Services;
using Microsoft.AspNetCore.Components;

namespace Connected.Components;

public partial class BreakpointProvider : UIComponent, IAsyncDisposable
{
	private Guid _breakPointListenerSubscriptionId;

	public Breakpoint Breakpoint { get; private set; } = Breakpoint.Always;

	[Parameter] public EventCallback<Breakpoint> OnBreakpointChanged { get; set; }

	[Inject] public IBreakpointService Service { get; set; }

	[Parameter]
	[Category(CategoryTypes.BreakpointProvider.Behavior)]
	public RenderFragment ChildContent { get; set; }

	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		await base.OnAfterRenderAsync(firstRender);

		if (firstRender == true)
		{
			var attachResult = await Service.Subscribe(SetBreakpointCallback);
			_breakPointListenerSubscriptionId = attachResult.SubscriptionId;
			Breakpoint = attachResult.Breakpoint;
			await OnBreakpointChanged.InvokeAsync(Breakpoint);
			StateHasChanged();
		}
	}

	private void SetBreakpointCallback(Breakpoint breakpoint)
	{
		InvokeAsync(() =>
		{
			Breakpoint = breakpoint;
			OnBreakpointChanged.InvokeAsync(breakpoint);
			StateHasChanged();
		}).AndForget();
	}

	public async ValueTask DisposeAsync() => await Service.Unsubscribe(_breakPointListenerSubscriptionId);
}
