@page "/Servers"
@using LANCommander.Pages.Servers.Components
@using Microsoft.EntityFrameworkCore;
@attribute [Authorize(Roles = "Administrator")]
@inject ServerService ServerService
@inject ServerProcessService ServerProcessService
@inject NavigationManager NavigationManager
@inject IMessageService MessageService

<PageHeader Title="Servers">
    <PageHeaderExtra>
        <Space Direction="DirectionVHType.Horizontal">
            @if (SelectedServers != null && SelectedServers.Count() > 0)
            {
                <SpaceItem>
                    <Button Type="@ButtonType.Primary" OnClick="() => StartServers()">Start</Button>
                    <Popconfirm OnConfirm="() => StopServers()" Title="Are you sure you want to kill these server processes?">
                        <Button Danger Type="@ButtonType.Primary">Stop</Button>
                    </Popconfirm>
                </SpaceItem>
            }
            <SpaceItem>
                <Search Placeholder="Search" @bind-Value="Search" BindOnInput DebounceMilliseconds="150" OnChange="() => LoadData()" />
            </SpaceItem>
            <SpaceItem>
                <Button OnClick="() => Add()" Type="@ButtonType.Primary">Add Server</Button>
            </SpaceItem>
        </Space>
    </PageHeaderExtra>
</PageHeader>

<TableColumnPicker @ref="Picker" Key="Servers" @bind-Visible="ColumnPickerVisible" />

<Table TItem="Server" DataSource="@Servers" Loading="@Loading" PageSize="25" @bind-SelectedRows="SelectedServers" Responsive>
    <Selection Key="@(context.Id.ToString())" />
    <PropertyColumn Property="s => s.Name" Sortable Hidden="@(Picker.IsColumnHidden("Name"))" />
     <PropertyColumn Property="s => s.Game" Hidden="@(Picker.IsColumnHidden("Game"))">
        <Image Src="@GetIcon(context.Game)" Height="32" Width="32" Preview="false"></Image>
        @context.Game?.Title
    </PropertyColumn>
    <PropertyColumn Property="s => s.CreatedOn" Format="MM/dd/yyyy hh:mm tt" Sortable Hidden="@(Picker.IsColumnHidden("Created On"))" />
    <PropertyColumn Property="s => s.CreatedBy" Sortable Hidden="@(Picker.IsColumnHidden("Created By"))">
        @context.CreatedBy?.UserName
    </PropertyColumn>
    <PropertyColumn Property="g => g.UpdatedOn" Format="MM/dd/yyyy hh:mm tt" Sortable Hidden="@(Picker.IsColumnHidden("Updated On"))" />
    <PropertyColumn Property="g => g.UpdatedBy" Sortable Hidden="@(Picker.IsColumnHidden("Updated By"))">
        @context.UpdatedBy?.UserName
    </PropertyColumn>
    <ActionColumn Title="" Style="text-align: right; white-space: nowrap">
        <TitleTemplate>
            <div style="text-align: right">
                <Button Icon="@IconType.Outline.Edit" Type="@ButtonType.Text" OnClick="() => OpenColumnPicker()" />
            </div>
        </TitleTemplate>
        <ChildContent>
            <ServerControl ServerId="context.Id" />
            <Space Direction="DirectionVHType.Horizontal">
                <SpaceItem>
                    <Button OnClick="() => Edit(context)">Edit</Button>
                </SpaceItem>
                <SpaceItem>
                    <Popconfirm OnConfirm="() => Delete(context)" Title="Are you sure you want to delete this server?">
                        <Button Icon="@IconType.Outline.Close" Type="@ButtonType.Text" Danger />
                    </Popconfirm>
                </SpaceItem>
            </Space>
        </ChildContent>
    </ActionColumn>
</Table>

@code {
    IEnumerable<Server> Servers { get; set; } = new List<Server>();

    bool Loading = true;

    string Search = "";

    IEnumerable<Server> SelectedServers;
    TableColumnPicker Picker;
    bool ColumnPickerVisible = false;

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            LoadData();

            Loading = false;

            StateHasChanged();
        }
    }

    private async Task LoadData()
    {
        var fuzzySearch = Search.ToLower().Trim();

        Servers = await ServerService.Get(s => s.Name.ToLower().Contains(fuzzySearch) || (s.Game != null && (s.Game.Title.ToLower().Contains(fuzzySearch) || s.Game.SortTitle.ToLower().Contains(fuzzySearch)))).OrderBy(s => s.Name).ToListAsync();
    }

    private void Add()
    {
        NavigationManager.NavigateTo("/Servers/Add");
    }

    private void Edit(Server server)
    {
        NavigationManager.NavigateTo($"/Servers/{server.Id}/General");
    }

    private async Task Delete(Server server)
    {
        Servers = new List<Server>();

        Loading = true;

        await ServerService.Delete(server);

        Servers = await ServerService.Get(x => true).OrderBy(s => s.Name).ToListAsync();

        Loading = false;
    }

    private string GetIcon(Game game)
    {
        var media = game?.Media?.FirstOrDefault(m => m.Type == Data.Enums.MediaType.Icon);

        if (media != null)
            return $"/api/Media/{media.Id}/Download?fileId={media.FileId}";
        else
            return "/favicon.ico";
    }

    private async Task StartServers()
    {
        foreach (var server in SelectedServers)
        {
            try
            {
                var status = ServerProcessService.GetStatus(server);

                if (status == ServerProcessStatus.Stopped || status == ServerProcessStatus.Error)
                {
                    ServerProcessService.StartServerAsync(server);
                }
            }
            catch { }
        }
    }

    private void StopServers()
    {
        foreach (var server in SelectedServers)
        {
            if (ServerProcessService.GetStatus(server) == ServerProcessStatus.Running)
                ServerProcessService.StopServer(server);
        }
    }

    private async Task OpenColumnPicker()
    {
        ColumnPickerVisible = true;
    }

    private async Task CloseColumnPicker()
    {
        ColumnPickerVisible = false;
    }
}
