using CMSMicroservice.Protobuf.Protos.Package;
using Google.Protobuf;
using Grpc.Core;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using MudBlazor;

namespace BackOffice.Pages.Package.Components;

public partial class CreateDialog
{
    [Inject] public PackageContract.PackageContractClient PackageContract { get; set; }
    [Parameter] public CreateNewPackageRequest Model { get; set; } = new();
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; }

    private bool _isLoading = false;
    private string _srcImage = "data:image/png;base64,[encoded data, 19220 characters]";
    private IBrowserFile? _imageFile;
    private long _maxAllowedSize = (1024 * 1024) * 200;

    private async Task OnImageFileSelect(IBrowserFile? file)
    {
        _imageFile = file;
        var buffer = new byte[file.Size];
        await file.OpenReadStream().ReadAsync(buffer);
        _srcImage = $"data:{file.ContentType};base64," + Convert.ToBase64String(buffer);
        StateHasChanged();
    }
    public async void CallCreateMethod()
    {
        _isLoading = true;
        StateHasChanged();

        if (string.IsNullOrWhiteSpace(Model.Title))
        {
            Snackbar.Add("لطفا عنوان را وارد کنید!", Severity.Warning);
            _isLoading = false;
            StateHasChanged();
            return;
        }
        if (string.IsNullOrWhiteSpace(Model.Description))
        {
            Snackbar.Add("لطفا توضیحات را وارد کنید!", Severity.Warning);
            _isLoading = false;
            StateHasChanged();
            return;
        }
        if (_imageFile == null)
        {
            Snackbar.Add("لطفا تصویر را انتخاب کنید!", Severity.Warning);
            _isLoading = false;
            StateHasChanged();
            return;
        }
        else
        {
            var imageBuffers = new byte[_imageFile.Size];
            await _imageFile.OpenReadStream(_maxAllowedSize).ReadAsync(imageBuffers);
            Model.ImageFile = new()
            {
                File = ByteString.CopyFrom(imageBuffers),
                Mime = _imageFile.ContentType,
                FileName = Path.GetFileNameWithoutExtension(_imageFile.Name)
            };
        }
        try
        {
            await PackageContract.CreateNewPackageAsync(Model);
            Submit();

        }
        catch (RpcException)
        {
            Snackbar.Add("خطای سرور", Severity.Error);
        }

        _isLoading = false;
        StateHasChanged();
    }
    void Submit() => MudDialog.Close(DialogResult.Ok(true));
    void Cancel() => MudDialog.Cancel();
}
