@using Moonlight.Features.Servers.Entities
@using MoonCore.Abstractions
@using MoonCoreUI.Services

@inject Repository<ServerVariable> ServerVariableRepository
@inject ToastService ToastService

@if (ImageVariable.AllowEdit)
{
    <div class="d-flex justify-content-between align-items-center">
        <div class="form-check form-switch form-switch-lg">
            <input @bind="Toggle" class="form-check-input" type="checkbox" role="switch">
        </div>
        <WButton OnClick="Update" CssClasses="btn btn-icon btn-primary">
            <i class="bx bx-sm bx-save"></i>
        </WButton>
    </div>
}
else
{
    <div class="input-group">
        <div class="form-check form-switch form-switch-lg">
            <input class="form-check-input" type="checkbox" role="switch" disabled="disabled"/>
        </div>
    </div>
}

@code
{
    [Parameter] public ServerVariable Variable { get; set; }

    [Parameter] public ServerImageVariable ImageVariable { get; set; }

    [Parameter] public Func<Task> OnChanged { get; set; }

    private bool Toggle;

    protected override void OnInitialized()
    {
        if (!string.IsNullOrEmpty(ImageVariable.Filter) && ImageVariable.Filter == "boolean")
            Toggle = Variable.Value.ToLower() == "true";
        else
            Toggle = Variable.Value.ToLower() == "1";
    }

    private async Task Update()
    {
        if (!string.IsNullOrEmpty(ImageVariable.Filter) && ImageVariable.Filter == "boolean")
            Variable.Value = Toggle ? "true" : "false";
        else
            Variable.Value = Toggle ? "1" : "0";

        ServerVariableRepository.Update(Variable);

        await ToastService.Success("Successfully changed variable");
        await OnChanged.Invoke();
    }
}