@*
 *                                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.
 *@
﻿<style>
    .full-width {
    width: 408px !important;
    }

    .column-cb {
        min-width: 30px;
        width: 30px;
    }

</style>

<EditForm EditContext="EditContext">
    <div class="d-flex flex-row fit-content">
        <div class="fit-content mr-3">
            <div class="form-row fit-content">
                <FormItemText Class="mr-2" Name="User name"     Enabled="@IsNew" @bind-Value="Value.UserName" Icon="icon-user-sm" />
                @if (Value.IsBuiltin || string.IsNullOrWhiteSpace(Value.Db))
                {
                    <FormItemText Class="mr-2" Name="Create within" Enabled="false" Value="Builtin" Icon="icon-annotate-sm" />
                }
                else
                {
                    <FormItemSelect Class="mr-2" Name="Create within" Enabled="@IsNew" @bind-Value="Value.Db" Icon="icon-annotate-sm" Values="@AllDatabases" />
                }
            </div>
            <div class="form-row fit-content">
                <FormItemPassword Class="full-width" Name="Password" Enabled="@IsEnabled" @bind-Value="Value.Password" />
            </div>

            <div class="form-row fit-content">
                <RolesSelector Value="@Value.Roles"
                               AllRoles="@AllRoles"
                               IsEnabled="@IsEnabled"
                               />
            </div>

        </div>
    </div>


</EditForm>

@code {
    [CascadingParameter] public IModalService Modal { get; set; } = null!;

    [Parameter] public string              Name       { get; set; } = $"newRole{++_count}";

    [Parameter]
    public UserInfoModel       Value
    {
        get => field;
        set
        {
            if (field == value)
                return;
            field = value;
            UpdateSelectable();
        }
    } = new();

    [Parameter]
    public List<RoleInDbModel> AllRoles
    {
        get;
        set 
        {
            if (field == value)
                return;
            field = value;
            UpdateSelectable();
        }
    } = [];

    [Parameter] public bool         IsEnabled    { get; set; } = true;
    [Parameter] public bool         IsNew        { get; set; }
    [Parameter] public List<string> AllDatabases { get; set; } = [];

    private static int _count;
    private EditContext EditContext => _editContext!;

    private EditContext? _editContext;

    public class SelectableString(string name, bool isSelected, Action<SelectableString, bool> update)
    {
        public override string ToString() => $"[{(IsSelected ? "X" : " ")}] {Name} {Db}";

        public string Name { get; } = name;
        public string Db   { get; init; } = string.Empty;

        public bool IsSelected
        {
            get;
            set
            {
                if (field == value)
                    return;
                field = value;
                update(this, field);
            }
        } = isSelected;
    }

    private List<SelectableString> SelectableRoles   { get; set; } = [];

    protected override void OnInitialized()
    {
        _editContext = new(this);
    }

    private void UpdateSelectable()
    {
        SelectableRoles = AllRoles
           .Select(x => 
                       new SelectableString(x.Role, Value.Roles.Any(y => IsSameRole(x, y)),UpdateSelectedRoles)
                       {
                           Db = x.Db 
                       }
            )
           .ToList();

        InvokeAsync(StateHasChanged);
    }

    private static bool IsSameRole(RoleInDbModel x, RoleInDbModel y) => 
        x.Role == y.Role 
     && (x.Db == y.Db || string.IsNullOrWhiteSpace(x.Db) || string.IsNullOrWhiteSpace(y.Db));

    private static bool IsSameRole(RoleInDbModel x, SelectableString y) => 
        x.Role == y.Name 
     && (x.Db == y.Db || string.IsNullOrWhiteSpace(x.Db) || string.IsNullOrWhiteSpace(y.Db));


    private void UpdateSelectedRoles(SelectableString role, bool isSelected)
    {
        var found = Value.Roles.FirstOrDefault(x => IsSameRole(x, role));
        if (isSelected)
        {
            if (found == null)
                Value.Roles.Add(new () { Role = role.Name, Db = role.Db});
        }
        else
        {
            if (found != null)
                Value.Roles.Remove(found);
        }
    }

}
