using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using wispro.sp.entity;
using wispro.sp.share.webViewObject;

namespace wispro.sp.api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private static List<Staff> CacheList = new List<Staff>();
        public IConfiguration Configuration { get; }

        public AccountController(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        
        [HttpGet,HttpPost,Route("Login")]
        public userToken Login(loginDto loginUser)
        {
            //添加验证代码
            spDbContext dbContext = new spDbContext();
            Staff staff = dbContext.Staffs.Where<Staff>(s => s.Account == loginUser.Name && s.Password == loginUser.Password).FirstOrDefault();

            if(staff != null)
            {
                return GetToken(staff);
            }
            else
            {
                return new userToken() { 
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    Name = null, 
                    Token = null 
                };
            }
            
        }

        [HttpGet,Route("GetUser")]
        public userToken GetUser()
        {
            if (User.Identity.IsAuthenticated)//如果Token有效
            {
                var name = User.Claims.First(x => x.Type == ClaimTypes.Name).Value;//从Token中拿出用户ID
                                                                                   //模拟获得Token
                spDbContext dbContext = new spDbContext();
                Staff staff = dbContext.Staffs.Where<Staff>(s => s.Account == name).FirstOrDefault();

                if (staff != null)
                {
                    return GetToken(staff);
                }
                else
                {
                    return new userToken() {StatusCode=System.Net.HttpStatusCode.NotFound, Name = null, Token = null };
                }
            }
            else
            {
                return new userToken() {StatusCode= System.Net.HttpStatusCode.NotFound, Name = null, Token = null };
            }
        }


        private userToken GetToken(Staff staff)
        {
            var claims = new Claim[]
            {
                new Claim("Id",staff.Id.ToString()),
                new Claim(ClaimTypes.Name,staff.Name),
                new Claim(ClaimTypes.Email,(staff.Mail==null)?"":staff.Mail),
                //new Claim(ClaimTypes.Role,"Admin"),
            };


            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:Key"]));
            var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expireTime = DateTime.Now.AddMinutes(20);
            
            var token = new JwtSecurityToken(
                issuer: Configuration["jwt:Issuer"],
                audience: Configuration["jwt:Audience"],
                claims: claims,
                notBefore: DateTime.Now,
                expires: expireTime,                
                signingCredentials: credential);

            
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            //建立UserToken物件後回傳client
            userToken userToken = new userToken()
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Name = staff.Name,
                Token = jwtToken,
                ExpireTime = expireTime
            };

            return userToken;

        }
    }
    
}
