@page "/expand"
@page "/expand/{messageId}"
@inherits LocalizableComponentBase

<div class="flex w-full h-full flex-col space-y-4">

	<section class="block relative w-full h-full neomorphInset is-nxsmall rounded-xl">
		<div class="flex flex-col space-y-4 p-4 md:p-5 w-full h-full absolute overflow-y-auto @SUtility.IfTrueThen(TimeSortingType is TimeSortingType.Descending, "flex-col-reverse")">

			@if (IsLoading)
			{
				<LoadingData />
			}

			@foreach (var message in Ancestors)
			{
				<Content CssContainer="ml-6 w-auto" IncludeExpand="false" Message="message"
							 OnMessageBoost="async (m) => await OnMessageBoost(m)" OnMessageDelete="async (m) => await OnMessageDelete(m)"
							 OnMessageFavourite="async (m) => await OnMessageFavourite(m)" OnMessageReply="async (m) => await OnMessageReply(m)"
							 OnMessageMediaDownload="async (m) => await OnMessageMediaDownload(m)"
							 OnUserBlock="async (u) => await OnUserBlock(u)" OnUserDirectMessage="async (u) => await OnUserDirectMessage(u)" OnUserSilence="async (u) => await OnUserSilence(u)" />
			}

			<Content CssContainer="is-nsmall" IncludeExpand="false" Message="CurrentMessage"
							 OnMessageBoost="async (m) => await OnMessageBoost(m)" OnMessageDelete="async (m) => await OnMessageDelete(m)"
							 OnMessageFavourite="async (m) => await OnMessageFavourite(m)" OnMessageReply="async (m) => await OnMessageReply(m)"
							 OnMessageMediaDownload="async (m) => await OnMessageMediaDownload(m)"
							 OnUserBlock="async (u) => await OnUserBlock(u)" OnUserDirectMessage="async (u) => await OnUserDirectMessage(u)" OnUserSilence="async (u) => await OnUserSilence(u)" />

			@foreach (var message in Descendants)
			{
				<Content CssContainer="ml-6 w-auto" IncludeExpand="false" Message="message"
							 OnMessageBoost="async (m) => await OnMessageBoost(m)" OnMessageDelete="async (m) => await OnMessageDelete(m)"
							 OnMessageFavourite="async (m) => await OnMessageFavourite(m)" OnMessageReply="async (m) => await OnMessageReply(m)"
							 OnMessageMediaDownload="async (m) => await OnMessageMediaDownload(m)"
							 OnUserBlock="async (u) => await OnUserBlock(u)" OnUserDirectMessage="async (u) => await OnUserDirectMessage(u)" OnUserSilence="async (u) => await OnUserSilence(u)" />
			}

		</div>
	</section>

</div>

@code {
	[CascadingParameter] CascadingState CascadingState { get; set; }
	[Inject] NavigationManager Navigation { get; set; }
	[Inject] IStorage DbStorage { get; set; }
	[Inject] ILocalStorageService LocalStorage { get; set; }
	[Inject] IBlazorDownloadFileService BlazorDownloadFileService { get; set; }
	[Inject] MessagesService MessagesService { get; set; }
	[Parameter] public string MessageId { get; set; }

	List<Message> Ancestors { get; set; } = new();
	Message CurrentMessage { get; set; } = new();
	List<Message> Descendants { get; set; } = new();

	TimeSortingType TimeSortingType { get; set; } = TimeSortingType.Ascending;

	protected override async Task OnInitializedAsync()
	{
		if (MessageId is { Length: 0 })
		{
			Navigation.NavigateTo("/");
			return;
		}

		var filters = await LocalStorage.GetItemAsync<ActionBarFilter>(nameof(ActionBarFilter));
		if (filters == default)
			await LocalStorage.SetItemAsync(nameof(ActionBarFilter), new ActionBarFilter());
		else
			TimeSortingType = filters.TimeSortingType;

		CurrentMessage = await DbStorage.GetMessage(MessageId);

		Ancestors = new List<Message>
		{
			new()
			{
				RootMessageId = default,
				MessageId = "51C698E3-7C28-4C90-9212-48D5C81DE089",
				User = Faker.GetRandomUser(),
				MessageType = (MessageType)Random.Shared.Next(0, 4),
				Title = CurrentMessage?.Title,
				Content = "<p>esempio di messaggio <b>precedente</b> a quello espanso</p>",
				Medias = new(),
				CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
				IsFavourite = Random.Shared.Next() % 2 == 0,
				BoostsCounter = Random.Shared.Next(0,100),
				IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
			}
		};

		Descendants = new List<Message>
		{
			new()
			{
				RootMessageId = default,
				MessageId = "0569A1DF-46FC-4485-9F11-F8CDFB794404",
				User = Faker.GetRandomUser(),
				MessageType = (MessageType)Random.Shared.Next(0, 4),
				Title = CurrentMessage?.Title,
				Content = "<p>esempio di messaggio <b>successivo</b> a quello espanso</p>",
				Medias = new(),
				CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
				IsFavourite = Random.Shared.Next() % 2 == 0,
				BoostsCounter = Random.Shared.Next(0,100),
				IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
			}
		};
		IsLoading = false;
	}

	void OnTimeSortingChanged(TimeSortingType timeSortingType)
	{
		TimeSortingType = timeSortingType;
	}

	async Task OnMessageReply(MessageForm messageForm)
	{
		var replyMessage = await MessagesService.SubmitMessage(messageForm);
		Descendants.Add(new()
			{
				MessageId = Guid.NewGuid().ToString(),
				Content = messageForm.Content?.ParseContent(messageForm.ContentType),
				CreatedAt = DateTime.UtcNow,
				MessageType = messageForm.MessageType,
				Medias = messageForm.Media.Select(m => new Media
				{
					FileName = m.FileName,
					AltText = m.AltText,
					ContentType = m.ContentType,
					Url = m.Base64Preview,
					Blob = m.Blob
				}).ToList(),
				Title = messageForm.Title,
				User = new MessageUser
				{
					UserId = CascadingState.User.Id,
					UserName = CascadingState.User.UserName,
					DisplayName = CascadingState.User.DisplayName,
					PictureUrl = CascadingState.User.PictureUrl,
					ProfileUrl = CascadingState.User.ProfileUrl,
					BackgroundUrl = CascadingState.User.BackgroundUrl
				},
			});
	}

	async ValueTask OnMessageBoost(Message message)
	{
		if (message.IsBoostedByCurrentUser) return;
		var boostedMessage = await MessagesService.BoostUnboostMessage(message);
		message.BoostsCounter += 1;

		//Add to the home page in the background
	}

	async ValueTask OnMessageFavourite(Message message)
	{
		var favouriteMessage = await MessagesService.FavouriteUnfavouriteMessage(message);
		message.IsFavourite = !message.IsFavourite;
	}

	async ValueTask OnMessageDelete(Message message)
	{
		var deleteResult = await MessagesService.DeleteMessage(message);
	}

	async ValueTask OnMessageMediaDownload(Media media)
	{
		await BlazorDownloadFileService.DownloadFileAsync(media.FileName, media.Blob, media.ContentType);
	}

	async ValueTask OnUserBlock(MessageUser messageUser)
	{
		var blockResult = await MessagesService.BlockUserFromMessage(messageUser);
	}

	async ValueTask OnUserDirectMessage(Message message)
	{
		var directMessage = await MessagesService.ReplyMessage(message, MessageType.Direct);
	}

	async ValueTask OnUserSilence(MessageUser messageUser)
	{
		var silenceResult = await MessagesService.SilenceUserFromMessage(messageUser);
	}
}