using System;
using System.Linq;
using FAuth.DataBase.Tables;
using FAuth.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace FAuth.Controllers.api
{
    /// <summary>
    /// 应用角色组对应
    /// </summary>
    public class App_RoleGroupController:ApiControllerBase<App_RoleGroupController>
    {
        public App_RoleGroupController(ILogger<App_RoleGroupController> logger,IServiceProvider service) : base(logger,service) {
        }
        /// <summary>
        /// 绑定指定应用和角色组
        /// </summary>
        /// <param name="appId">应用编号</param>
        /// <param name="roleGroupId">角色组编号</param>
        /// <returns>是否成功</returns>
        [HttpPost]
        public bool Binding(int appId,int roleGroupId) {
            var aQu = this.Db.Apps.Where(m => m.Id == appId);
            if(!aQu.Any()) {
                throw new ApiException("没有找到指定的应用");
            }
            var rQu = this.Db.RoleGroups.Where(m => m.Id == roleGroupId);
            if(!rQu.Any()) {
                throw new ApiException("没有找到指定的角色组");
            }
            var arQu = this.Db.App_RoleGroups.Where(m => m.AppId == appId && m.RoleGroupId == roleGroupId);
            if(!arQu.Any()) {
                var model = new App_RoleGroup {
                    AppId = appId,
                    RoleGroupId = roleGroupId,
                };
                this.Db.Entry(model).State = EntityState.Added;
                this.Db.SaveChangesAsync().Wait();
            }
            return true;
        }
        /// <summary>
        /// 解除指定应用和角色组绑定
        /// </summary>
        /// <param name="appId">应用编号</param>
        /// <param name="roleGroupId">角色组编号</param>
        /// <returns>解绑是否成功</returns>
        [HttpPost]
        public bool Unbind(int appId,int roleGroupId) {
            var aQu = this.Db.Apps.Where(m => m.Id == appId);
            if(!aQu.Any()) {
                throw new ApiException("没有找到指定的应用");
            }
            var rQu = this.Db.RoleGroups.Where(m => m.Id == roleGroupId);
            if(!rQu.Any()) {
                throw new ApiException("没有找到指定的角色组");
            }
            var arQu = this.Db.App_RoleGroups.Where(m => m.AppId == appId && m.RoleGroupId == roleGroupId);
            if(arQu.Any()) {
                foreach(var item in arQu) {
                    this.Db.Entry(item).State = EntityState.Deleted;
                }
                this.Db.SaveChangesAsync().Wait();
            }
            return true;
        }
    }
}
