@page "/plants/add"
@using Models.BaseData
@inject IPlantsUtils PlantsUtils
@using Microsoft.AspNetCore.Components.Forms

<div class="form">
    <h3>Save Plant</h3>
    <EditForm Model="@PlantModel" OnValidSubmit="AddPlant" >
        <DataAnnotationsValidator />
        
        <div class="row">
            <div class="col">
                <input type="text" class="form-control" placeholder="Plant Name" @bind="PlantModel.Name" />
                <ValidationMessage For="@(() => PlantModel.Name)" />
            </div>
        </div>

        <div class="row">
            <div class="col">
                <textarea rows="10" class="form-control" placeholder="Plant Data" @bind="PlantModel.KnowledgeBase" />
                <ValidationMessage For="@(() => PlantModel.KnowledgeBase)" />
            </div>
        </div>
    

        <div class="row">
            <div class="col">
                image:<br/>
                <InputFile id="image" name="image" class="form-control" OnChange="OnInputFileChange" />
                <ValidationMessage For="@(() => PlantModel.Base64Icon)" />
            </div>
        </div>

        <div class="row">
            <div class="col">
                <button class="btn btn-primary" type="submit">Add Plant</button>
            </div>
        </div>
    </EditForm>
</div>

<style>
    .form {
        display: flex;
        flex-direction: column;
        align-items: center;
        align-content: center;
    }

    .form-control {
        margin: 5px 5px;
    }
</style>

@code {
    protected SavePlantViewModel PlantModel { get; set; } = new();

    protected async Task AddPlant()
    {
        var response = await PlantsUtils.Add(PlantModel);
        if (response.IsSuccessStatusCode)
        {
            NavigationManager.NavigateTo("/plants/list");
        }
    }

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        var buf = new byte[e.File.Size];
        try
        {
            await e.File.OpenReadStream(maxAllowedSize:  1000000).ReadAsync(buf);
            PlantModel.Base64Icon =  Convert.ToBase64String(buf);
            StateHasChanged();
        }
        catch
        {
            await SwalUtils.ShowSwal("","Image size should be less than 1 MB.", icon: SweetAlertIcon.Error);
        }
    }
}