@page "/plugins"
@using DiscordBotWebUI.Components.CustomTags
@using DiscordBotWebUI.Models
@using DiscordBotWebUI.ServerCommunication
@inject DialogService DialogService

<Marketplace PluginModels="_PluginModels" OnPluginDownloadClick="OnModelSelected"/>


@code {
    private List<PluginModel> _PluginModels;

    [Inject]
    public ApiHandler ApiHandler { get; set; }

    private async void OnModelSelected(string itemName)
    {
        ApiResponse response = await ApiHandler.PostAsync("/api/plugin/install", new Dictionary<string, string>()
        {
            {"pluginName", itemName}
        });
        if(!response.Success)
        {
            Console.WriteLine(response.Message);
            return;
        }

        await DialogService.OpenAsync<ProgressDialog>($"Installing {itemName}", new Dictionary<string, object>()
        {
            {"ProgressUrl", "/plugin/download/progress"},
            {"FirstMessage", itemName}
        }, new DialogOptions()
        {
            Draggable = false,
            CloseDialogOnEsc = false,
            CloseDialogOnOverlayClick = false,
            ShowClose = false
        });

    }

    protected override async Task OnInitializedAsync()
    {
        ApiResponse response = await ApiHandler.GetAsync("/api/plugin/list/online");

        if (!response.Success)
        {
            return;
        }

        string jsonStr = response.Message;
        var result = await JsonManager.ConvertFromJson<List<PluginModel>>(jsonStr);

        if (result != null)
        {
            _PluginModels = result;
        }
    }

}