@using Wave.Services
@using Wave.Data

@inject ImageService Images
@inject IStringLocalizer<ArticleEditor> Localizer

<ModalComponent Id="@Id" ShowCloseButton="false">
	<ChildContent>
		@if (Image != null) {
			<figure>
				<img src="/images/@(Image)" alt=""/>
			</figure>
		}
		<FileUploadComponent FileUploadedCallback="FileChanged"/>
		
		<InputLabelComponent LabelText="@Localizer["Image_Description_Label"]">
			<InputText class="input input-bordered w-full" maxlength="2048"
			           @bind-Value="@ImageDescription" 
			           placeholder="@Localizer["Image_Description_Placeholder"]" 
			           autocomplete="off" />
		</InputLabelComponent>
	</ChildContent>
	<Actions>
		<button class="btn btn-primary" @onclick="Save">@Localizer["Image_Add_Submit"]</button>
		<form method="dialog">
			<button type="submit" class="btn btn-error" @onclick="Cancel">@Localizer["Image_Add_Abort"]</button>
		</form>
	</Actions>
</ModalComponent>

@code {
	[Parameter]
	public required string Id { get; set; }
	[Parameter]
	public required EventCallback<ArticleImage> ImageAdded { get; set; }

	private Guid? Image { get; set; }
	private string ImageDescription { get; set; } = string.Empty;
	
	private async Task FileChanged(string tempPath) {
		if (Image is { } img) {
			Image = null;
			Images.Delete(img);
		}

		Image = await Images.StoreImageAsync(tempPath);
	}

	private async Task Save() {
		if (Image is null) return;

		await ImageAdded.InvokeAsync(new ArticleImage {
			Id = Image.Value,
			ImageDescription = ImageDescription
		});

		Image = null;
		ImageDescription = string.Empty;
	}

	private void Cancel() {
		if (Image is { } img) {
			Image = null;
			Images.Delete(img);
		}
		ImageDescription = string.Empty;
	}

}
