using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.User;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Windows;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NEIntelligentControl2.Service.User
{
    /// <summary>
    /// 用户控制
    /// </summary>
    public class UserManager
    {
        /// <summary>
        /// 是否登录
        /// </summary>
        public bool IsLogined { get; set; }
        /// <summary>
        /// 是否临时登录
        /// </summary>
        public bool IsTempLogin { get; set; }
        /// <summary>
        /// 用户
        /// </summary>
        public UserInfo User { get; set; }

        private string _Url;

        private WEBHelper _WEBHelper;
        public UserManager(WEBHelper wh, UrlManager um)
        {
            _WEBHelper = wh;
            _Url = um.ServicePath;
        }

        /// <summary>
        /// 用户名密码登录
        /// </summary>
        /// <returns></returns>
        internal bool Login(string v1, string v2)
        {
            var v = _WEBHelper.HttpPostBody<UserInfo>($"{_Url}/user/login", new { Username = v1, Password = v2 });
            if (v == null) return false;
            User = v;
            IsLogined = true;
            _WEBHelper.Token = v.Token;
            CheckPassword();
            return true;
        }

        /// <summary>
        /// 指纹登录
        /// </summary>
        /// <returns></returns>
        internal bool Login(string v1)
        {
            string s = GetMD5(v1);
            var v = _WEBHelper.HttpGetJSON<UserInfo>($"{_Url}/user/token?key={s}");
            if (v == null) return false;
            User = v;
            IsLogined = true;
            _WEBHelper.Token = v.Token;
            return true;
        }

        private string GetMD5(string v1)
        {
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(v1));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                sb.Append(s[i].ToString("X"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获取所有指纹
        /// </summary>
        internal List<string> GetAllFingers()
        {
            return _WEBHelper.HttpGetJSON<List<string>>($"{_Url}/user/fingers");
        }

        /// <summary>
        /// 注销用户
        /// </summary>
        public void Logout()
        {
            User = null;
            IsLogined = false;
            _WEBHelper.Token = null;
        }

        /// <summary>
        /// 临时登录
        /// </summary>
        internal bool TempLogin()
        {
            IsTempLogin = true;
            UserWindow uw = App.ServiceProvider.GetService(typeof(UserWindow)) as UserWindow;
            bool b = uw.Show("User.PageFingerprint");
            IsLogined = false;
            return b;
        }

        /// <summary>
        /// 检查密码
        /// </summary>
        private void CheckPassword()
        {
            if(User == null) return;
            if (!User.IsPasswordSecurity)
            {
                var b = MessageWindow.ShowMessage("密码安全性较低，必须包含大写字母，小写字母，数字以及特殊字符中的3种，并且不能少于8位！是否修改密码？");
                if (b)
                {
                    UserEdit();
                }
            }
        }

        /// <summary>
        /// 用户编辑
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        internal void UserEdit()
        {
            UserWindow uw = App.ServiceProvider.GetService(typeof(UserWindow)) as UserWindow;
            bool b = uw.Show("User.PageUserEdit", this.User);
        }

        internal void UserAdd()
        {
            UserWindow uw = App.ServiceProvider.GetService(typeof(UserWindow)) as UserWindow;
            bool b = uw.Show("User.PageUserEdit");
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        internal string RegisterUser(UserInfo userInfo)
        {
            bool b = CheckPassword(userInfo.Password);
            if (!b)
            {
                return "密码必须大于8位并且包含大写字母，小写字母，数字以及特殊字符中的任意3种！";
            }
            try
            {
                var str = _WEBHelper.HttpPostBodyString($"{_Url}/user/register", userInfo);
                return str;
            }
            catch (Exception e)
            {
                return "注册用户出现错误：" + e.Message;
            }
        }
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <returns></returns>
        internal string UpdateUser(UserInfo userInfo)
        {
            bool b = CheckPassword(userInfo.Password);
            if (!b)
            {
                return "密码必须大于8位并且包含大写字母，小写字母，数字以及特殊字符中的任意3种！";
            }
            try
            {
                var str = _WEBHelper.HttpPostBodyString($"{_Url}/user/update", userInfo);
                return str;
            }
            catch (Exception e)
            {
                return "修改用户出现错误：" + e.Message;
            }
        }

        private bool CheckPassword(string psd)
        {
            if (psd.Length < 8)
            {
                return false;
            }
            string[] ps = new string[] { "(?=.*[a-z])", "(?=.*[A-Z])", "(?=.*\\d)", "(?=.*[ !\"\"#$%&'()*+,-./:;<=>?@\\[\\]\\^_`{|}~])" };
            int count = 0;
            foreach (var s in ps)
            {
                if (Regex.IsMatch(psd, s))
                {
                    ++count;
                }
            }
            return count > 2;
        }
    }
}
