using System.Collections.Generic;
using System.Linq;
using FAuth.DataBase;
using FAuth.Extensions.Decryptor;

namespace FAuth.Extensions.Account
{
    /// <summary>
    /// 账号帮助类
    /// </summary>
    public class AccountHelper
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        public FAuthDb Db { get; set; }
        /// <summary>
        /// 用户凭据加密提供器
        /// </summary>
        public IUserTicketDryptor TicketDryptor { get; set; }

        public AccountHelper(FAuthDb db,IUserTicketDryptor ticketDryptor) {
            this.Db = db;
            this.TicketDryptor = ticketDryptor;
        }

        /// <summary>
        /// 查询用户是否为FAuth系统管理员
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns>是否为FAuth系统管理员</returns>
        public bool IsSystemAdmin(int userId) {
            var qu =
                from arg in this.Db.App_RoleGroups
                join rgr in this.Db.RoleGroup_Roles on arg.RoleGroupId equals rgr.RoleGroupId
                join ru in this.Db.Role_Users on rgr.RoleId equals ru.RoleId
                where arg.AppId == 1 && arg.RoleGroupId == 1 && ru.UserId == userId
                select 1;
            return qu.Any();
        }

        /// <summary>
        /// 用户是否不是系统管理员
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns>是否不是管理员</returns>
        public bool IsNotSystemAdmin(int userId) => !IsSystemAdmin(userId);

        /// <summary>
        /// 查询票据是否为系统管理员
        /// </summary>
        /// <param name="userTicket">用户票据</param>
        /// <returns>是管理员True，否则false</returns>
        public bool IsSystemAdmin(string userTicket) => IsSystemAdmin(this.TicketDryptor.Decrypt(userTicket).Id);

        /// <summary>
        /// 查询票据是否不是系统管理员
        /// </summary>
        /// <param name="userTicket">用户票据</param>
        /// <returns>是管理员False，否则True</returns>
        public bool IsNotSystemAdmin(string userTicket) => !IsSystemAdmin(userTicket);
    }
}
