using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Xaml.Controls.Primitives;
using Sonex.DBWrapper;
using System;
using System.Security;
using System.Threading.Tasks;
using Windows.Networking;
using static System.Net.Mime.MediaTypeNames;

namespace Sonex.Client.Models;

public partial class GroupModel : ObservableObject
{
    [ObservableProperty]
    private int id;

    [ObservableProperty]
    private string name = string.Empty;

    [ObservableProperty]
    private string description = string.Empty;
    public string DisplayName
    {
        get
        {
            var text = name.Replace("group_", "").Replace('_', ' ').Trim();
            return string.IsNullOrEmpty(text)
                ? string.Empty
                : char.ToUpper(text[0]) + text.Substring(1);
        }
    }
    [ObservableProperty]
    private string[] grantedPermission = [];

    partial void OnNameChanged(string value) => OnPropertyChanged(nameof(DisplayName));

    public static Task<DB.SingleResult<GroupModel>> Get(string name)
    {
        return DB.QuerySingleAsync<GroupModel>("SELECT * FROM sonex.v_group_permissions WHERE name = @group_Name LIMIT 1;",
            new { group_Name = name });
    }

    public static Task<DB.Result<GroupModel>> GetAll()
    {
        return DB.QueryListAsync<GroupModel>("SELECT * FROM sonex.v_group_permissions;");
    }

    public static Task<DB.SingleResult<int>> Create(string name, string description)
    {
        return DB.QuerySingleAsync<int>("SELECT sonex.groups_create(@GroupName, @Description); ",
        new { GroupName = name, Description = description });
    }

    public static Task<DB.SingleResult<bool>> Delete(string name)
    {
        return DB.QuerySingleAsync<bool>("SELECT sonex.groups_delete(@GroupName); ",
        new { GroupName = name });
    }
    public static Task<DB.SingleResult<bool>> Update(string name, string newName, string description)
    {
        return DB.QuerySingleAsync<bool>("SELECT sonex.groups_update(@GroupName, @NewGroupName, @Description);",
            new { GroupName = name, NewGroupName = newName, Description = description });
    }
    public static Task<DB.SingleResult<bool>> AddPermission(string name, string permission)
    {
        return DB.QuerySingleAsync<bool>("SELECT sonex.groups_permissions_add(@GroupName, @Permission);",
            new { GroupName = name, Permission = permission});
    }

    public static Task<DB.SingleResult<bool>> RemovePermission(string name, string permission)
    {
        return DB.QuerySingleAsync<bool>("SELECT sonex.groups_permissions_remove(@GroupName, @Permission);",
            new { GroupName = name, Permission = permission });
    }


}
