@page "/admin/onboarding"
@using Microsoft.Extensions.Options
@using Rms.Risk.Mango.Services.Context
@attribute [Authorize]

@inject IDatabaseConfigurationService DatabaseConfig
@inject IOptions<DbMangoSettings>     Settings

@*
 *                                dbMango
 *
 * Copyright 2025 Deutsche Bank AG
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@

<h3>Onboarding</h3>

<AuthorizedOnly Policy="AdminAccess" Resource="@Settings.Value.Initial">

    <div class="flex-stack-vertical">
        <TableControl Items="@_configs" 
                      Class="table table-hover table-striped table-forge table-forge-striped fit-content" 
                      Selectable="true" 
                      RowClass="@(x => x.Name == _selectedRecord.Name ? "table-active" : "")"
                      SelectionChanged="@OnSelectionChanged"
            >
            <TableColumnControl Name="Name"             Field="Name" />
            <TableColumnControl Name="Contacts"         Field="Contacts" />
            <TableColumnControl Name="Database"         Field="MongoDbDatabase" />
            <TableColumnControl Name="Url"              Field="MongoDbUrl" />
        </TableControl>

        <div class="mt-4">
            <DatabaseOnboardingControl Name="@_selectedRecord.Name" Value="@_selectedRecord.Value" OnRefresh="@Refresh"/>
        </div>
    </div>

</AuthorizedOnly>

@code {

    public class DisplayRecord
    {
        public string                         Name            { get; set; } = "";
        public string                         Contacts        => Value.Contacts;
        public string                         MongoDbUrl      => Value.Config.MongoDbUrl;
        public string                         MongoDbDatabase => Value.Config.MongoDbDatabase;
        public DatabasesConfig.DatabaseConfig Value           { get; set; } = new();
    }

    private List<DisplayRecord> _configs       = [];
    private DisplayRecord       _selectedRecord = new();

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
            return Task.CompletedTask;

        return Refresh();
    }

    private void OnSelectionChanged((dynamic Row, string Col) data)
    {
        _selectedRecord = (DisplayRecord)data.Row;
        InvokeAsync(StateHasChanged);
    }

    private async Task Refresh()
    {
        var oldSelected = _selectedRecord.Name;

        await DatabaseConfig.Reload();
        _configs = DatabaseConfig.Databases
           .OrderBy(x => x.Key)
           .Select(x => 
                       new DisplayRecord
                       {
                           Name  = x.Key                          ,
                           Value = x.Value.Clone()
                       })
           .ToList();

        _selectedRecord =  _configs.FirstOrDefault(x => x.Name == oldSelected)
                       ?? _configs.First();
        
        await InvokeAsync(StateHasChanged);
    }

}
