using System;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc;
using Falcon.Extend;
using FAuth.DataBase;
using System.Linq;
using FAuth.DataBase.Tables;
using Microsoft.EntityFrameworkCore;
namespace FAuth.Controllers.api
{
    /// 
    /// 应用程序控制器
    /// 
    public class AppController:ApiControllerBase
    {
        public AppController(ILogger logger,IServiceProvider service) : base(logger,service) {
        }
        /// 
        /// 添加新应用
        /// 
        /// 应用名称
        /// 应用说明
        /// 应用信息
        [HttpPost]
        [ProducesResponseType(typeof(Apps),200)]
        public Apps AddNewApp(string appName,string description) {
            if(appName.IsNullOrEmpty()) {
                throw new ArgumentNullException(nameof(appName));
            }
            var qu = this.Db.Apps.Where(m => m.Name == appName);
            if(qu.Any()) {
                throw new Exception($"应用{appName}已经存在,不可以重复创建!");
            }
            var newApp = new Apps {
                Name = appName,
                Description = description,
            };
            this.Db.Entry(newApp).State = EntityState.Added;
            this.Db.SaveChangesAsync().Wait();
            return newApp;
        }
        [HttpPost]
        public bool RemoveApp(string appName) {
            if(appName.IsNullOrEmpty()) {
                throw new ArgumentNullException(nameof(appName));
            }
            var qu = this.Db.Apps.Where(m => m.Name == appName);
            foreach(var item in qu) {
                this.Db.Entry(item).State = EntityState.Deleted;
            }
            this.Db.SaveChangesAsync().Wait();
            return true;
        }
        /// 
        /// 查询app是否注册
        /// 
        /// app名称
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(Apps),200)]
        public Apps GetApps(string appName) {
            if(string.IsNullOrEmpty(appName))
                throw new ArgumentException("message",nameof(appName));
            var qu = this.Db.Apps.Where(m => m.Name == appName);
            if(qu.Any()) {
                return qu.First();
            } else {
                throw new Exception("没有找到该应用");
            }
        }
    }
}