@implements IDisposable

@inject IJSRuntime JsRuntime

<div class="file-item" @onclick:stopPropagation @onclick:preventDefault @onclick="Click" @oncontextmenu="Click">
    <input id="@ItemId" type="radio" name="@RadioName" hidden>
    @for (int i = 0; i < Model.Level; i++)
    {
        <div class="indent-guide"></div>
    }
    <div class="file-icon">
        <span class="mdi @Icon"></span>
    </div>
    <HierachyItemName Model="Model" />
    <HierachyItemDiagnostics Model="Model" />
    <HierachyItemModified Model="Model" />
</div>

@code {
    [CascadingParameter]
    private ScriptWorkspace Workspace { get; set; } = null!;

    [CascadingParameter(Name = "HierachyItemRadioName")]
    protected string RadioName { get; set; } = "script-explorer-item";

    [Parameter, EditorRequired]
    public ScriptFileModel Model { get; set; } = default!;

    Guid ItemId = Guid.NewGuid();

    private string Icon => "mdi-language-csharp";

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (!firstRender) return;

        Model.OnModified += OnModified;
        Model.OnDiagnosticsChanged += OnDiagnosticsChanged;
    }

    private void OnModified()
    {
        this.InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }

    private void OnDiagnosticsChanged(int warningCount, int errorCount)
    {
        this.InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }

    private async Task Click()
    {
        await JsRuntime.InvokeVoidAsync("SetRadioChecked", ItemId);
        await Workspace.SelectFile(this.Model);
    }

    public void Dispose()
    {
        Model.OnModified -= OnModified;
        Model.OnDiagnosticsChanged -= OnDiagnosticsChanged;
        GC.SuppressFinalize(this);
    }
}
