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

namespace BackOffice.Pages.Role.Components;

public partial class CreateDialog
{
    [Inject] public RoleContract.RoleContractClient RoleContract { get; set; }
    [Parameter] public CreateNewRoleRequest 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.Name))
        {
            Snackbar.Add("لطفا عنوان لاتین را وارد کنید!", Severity.Warning);
            _isLoading = false;
            StateHasChanged();
            return;
        }


        try
        {
            await RoleContract.CreateNewRoleAsync(Model);
            Submit();

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

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