@using DiscordBotCore
@using DiscordBotCore.Plugin
@using DiscordBotWebUI.Types

<RadzenDataGrid AllowColumnResize="true" PageSize="5" AllowPaging="true" PagerHorizontalAlign="HorizontalAlign.Left" Data="ListedItems">
    <Columns>
        <RadzenDataGridColumn Property="@nameof(MarketItem.Name)" Title="Item Name"></RadzenDataGridColumn>
        <RadzenDataGridColumn Property="@nameof(MarketItem.Author)" Title="Item Author"></RadzenDataGridColumn>
        <RadzenDataGridColumn Property="@nameof(MarketItem.Description)" Title="Item Description"></RadzenDataGridColumn>
        <RadzenDataGridColumn Property="@nameof(MarketItem.Type)" Title="Item type"></RadzenDataGridColumn>
        <RadzenDataGridColumn Title="Item Download">
            <Template Context="item">
                <RadzenButton Click="() => DownloadAction(item.Name, item.Type)">Download</RadzenButton>
            </Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>

<RadzenProgressBar Value="_ProgressValue" Visible="_ProgressBarVisible"/>

@code {
    private float _ProgressValue  = .0f;
    private bool  _ProgressBarVisible = false;
    

    [Parameter]
    public List<MarketItem> ListedItems { get; set; }
    
    public async void DownloadAction(string name, ItemType type)
    {
        switch (type)
        {
            case ItemType.Module:
                await DownloadModule(name);
                break;
            case ItemType.Plugin:
                await DownloadPlugin(name);
                break;
        }
    }
    
    private async Task DownloadModule(string moduleName)
    {
        _ProgressBarVisible = true;
        IProgress<float> downloadProgress = new Progress<float>(p => {
            _ProgressValue = p;
            StateHasChanged();
        });
        await Application.CurrentApplication.ModuleManager.InstallModule(moduleName, downloadProgress);
        _ProgressBarVisible = false;
    }
    
    private async Task DownloadPlugin(string pluginName)
    {
        _ProgressBarVisible = true;
        IProgress<float> downloadProgress = new Progress<float>(p => {
            _ProgressValue = p;
            StateHasChanged();
        });
        PluginOnlineInfo? pluginInfo       = await Application.CurrentApplication.PluginManager.GetPluginDataByName(pluginName);
        if (pluginInfo is null)
            return;

        await Application.CurrentApplication.PluginManager.InstallPlugin(pluginInfo, downloadProgress);

        _ProgressBarVisible = false;
    }
}