@namespace Radzen.Blazor
@using Microsoft.AspNetCore.Components.Forms
@using Radzen.Blazor.Spreadsheet
@using Radzen.Documents.Spreadsheet
@inherits RadzenSpreadsheetToolBase

<RadzenButton Variant="Variant.Text" ButtonStyle="ButtonStyle.Base" class="rz-fileupload-choose rz-button-icon-only" ButtonType="ButtonType.Button"
    Disabled=@IsDisabled Size="ButtonSize.Small"
    title=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_InsertImage)) ?? "Insert Image")>
    <InputFile OnChange=@OnFileSelectedAsync accept="image/*" disabled=@IsDisabled />
    <i class="notranslate rzi">image</i>
</RadzenButton>

@code {
    protected override SpreadsheetFeature? Feature => SpreadsheetFeature.Images;

    private async Task OnFileSelectedAsync(InputFileChangeEventArgs e)
    {
        if (Worksheet is null || Worksheet.Selection.Cell == CellRef.Invalid)
        {
            return;
        }

        var file = e.File;
        if (file is null)
        {
            return;
        }

        using var stream = file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
        using var ms = new System.IO.MemoryStream();
        await stream.CopyToAsync(ms);

        var address = Worksheet.Selection.Cell;
        var image = new SheetImage
        {
            AnchorMode = DrawingAnchorMode.OneCellAnchor,
            From = new CellAnchor { Row = address.Row, Column = address.Column },
            Width = 2000000,
            Height = 1500000,
            Data = ms.ToArray(),
            ContentType = file.ContentType ?? "image/png",
            Name = file.Name
        };

        if (Spreadsheet is not null)
        {
            var command = new InsertImageCommand(Worksheet, image);
            await Spreadsheet.ExecuteAsync(command);
        }
    }
}
