@using LANCommander.Data.Enums
@using LANCommander.Data.Models
@using LANCommander.Extensions;
@inject NavigationManager NavigationManager

<Space Direction="DirectionVHType.Vertical" Size="@("large")" Style="width: 100%">
    @if (Values == null || Values.Count == 0)
    {
        <Empty />
    }

    <SpaceItem>
        <Table TItem="ServerHttpPath" DataSource="@Values" HidePagination="true" Responsive>
            <PropertyColumn Property="p => p.LocalPath" Title="Local Path">
                <FilePicker @bind-Value="context.LocalPath" AllowDirectories Title="Select Local Path" Root="@WorkingDirectory" />
            </PropertyColumn>
            <PropertyColumn Property="p => p.Path">
                <Input Type="text" @bind-Value="context.Path" />
            </PropertyColumn>
            <ActionColumn>
                <Space Style="display: flex; justify-content: end">
                    @if (context != null && context.Id != Guid.Empty)
                    {
                        <SpaceItem>
                            <a class="ant-btn ant-btn-text ant-btn-icon-only" href="@NavigationManager.ToAbsoluteUri($"Server/{ServerId}/{context.Path.TrimStart('/')}")" target="_blank">
                                <Icon Type="@IconType.Outline.Eye" />
                            </a>
                        </SpaceItem>
                    }
                    <SpaceItem>
                        <Button OnClick="() => Remove(context)" Type="@ButtonType.Text" Danger Icon="@IconType.Outline.Close" />
                    </SpaceItem>
                </Space>
            </ActionColumn>
        </Table>
    </SpaceItem>

    <SpaceItem>
        <GridRow Justify="end">
            <GridCol>
                <Button OnClick="Add" Type="@ButtonType.Primary">Add Path</Button>
            </GridCol>
        </GridRow>
    </SpaceItem>
</Space>

@code {
    [Parameter] public ICollection<ServerHttpPath> Values { get; set; }
    [Parameter] public EventCallback<ICollection<ServerHttpPath>> ValuesChanged { get; set; }
    [Parameter] public Guid ServerId { get; set; }
    [Parameter] public string WorkingDirectory { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (Values == null)
            Values = new List<ServerHttpPath>();

        if (ValuesChanged.HasDelegate)
            await ValuesChanged.InvokeAsync(Values);

        StateHasChanged();
    }

    private async Task Add()
    {
        if (Values == null)
            Values = new List<ServerHttpPath>();

        Values.Add(new ServerHttpPath
        {
            ServerId = ServerId
        });

        if (ValuesChanged.HasDelegate)
            await ValuesChanged.InvokeAsync(Values);

        StateHasChanged();
    }

    private async Task Remove(ServerHttpPath httpPath)
    {
        Values.Remove(httpPath);

        if (ValuesChanged.HasDelegate)
            await ValuesChanged.InvokeAsync(Values);

        StateHasChanged();
    }
}
