using AudioWallpaper.Entity;
using AudioWallpaper.SSO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AudioWallpaper {
    public class SSOManager {
        public readonly static String StorageDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AudioWallpaper";

        private static TokenManager _tokenManager = new TokenManager(new EncryptedFileTokenStore(StorageDirectory));

        public static UserInfoSet? userInfoSet = null;

        public SSOManager() {
            AuthManager.Instance.OnLoginSuccess += OnLoginSuccess;
            AuthManager.Instance.OnLoginFailed += OnloginFailed;
            AuthManager.Instance.OnLogoutSuccess += OnLogoutSuccess;
            AuthManager.Instance.OnLogoutFailed += OnLogoutFailed;
            AuthManager.Instance.OnRevokeTokenSuccess += OnRevokeTokenSuccess;
            AuthManager.Instance.OnRevokeTokenFailed += OnRevokeTokenFailed;
            AuthManager.Instance.OnRefreshTokenSuccess += OnRefreshTokenSuccess;
            AuthManager.Instance.OnRefreshTokenFailed += OnRefreshTokenFailed;
            AuthManager.Instance.OnGetUserInfoSuccess += OnGetUserInfoSuccess;
            AuthManager.Instance.OnGetUserInfoFailed += OnGetUserInfoFailed;
            AuthManager.Instance.OnAuthStatusChanged += OnAuthStatusChanged;
            Console.WriteLine(StorageDirectory);
        }

        

        public async Task Initialize() {

            await ReLogin();

            Console.WriteLine("sso初始化完成");

        }
        #region 登录事件回调处理
        /// <summary>
        /// 退出登录失败回调
        /// </summary>
        /// <param name="obj">错误信息</param>
        private void OnLogoutFailed(string obj) {
            Console.WriteLine("登出失败:" + obj);
        }
        /// <summary>
        /// 退出登录成功回调
        /// </summary>
        private void OnLogoutSuccess() {
            Console.WriteLine("登出成功");
            //清除本地存储的令牌
            _tokenManager.ClearToken();
            if (SetFrom.setFrom == null) {
                return;
            }
            SetFrom.setFrom.ApplyModifications(
            new UIModification { ControlName = "P_NO_Login", PropertyName = "Visible", Value = true },
                 new UIModification { ControlName = "P_Login", PropertyName = "Visible", Value = false },
                 new UIModification { ControlName = "L_UserName", PropertyName = "Text", Value = string.Empty },
                 new UIModification { ControlName = "L_Welcome", PropertyName = "Text", Value = string.Empty }
                 );

        }
        /// <summary>
        /// 撤销令牌失败回调
        /// </summary>
        /// <param name="obj">错误信息</param>
        private void OnRevokeTokenFailed(string obj) {
            Console.WriteLine("撤销令牌失败:" + obj);
        }
        /// <summary>
        /// 撤销令牌成功回调
        /// </summary>
        private void OnRevokeTokenSuccess() {
            Console.WriteLine("撤销令牌成功");
            //清除本地存储的令牌
            _tokenManager.ClearToken();
        }

        /// <summary>
        /// 刷新令牌失败回调
        /// </summary>
        /// <param name="obj">失败信息</param>
        private void OnRefreshTokenFailed(string obj) {
            Console.WriteLine("刷新令牌失败:" + obj);
            //重新登录
            //ReLogin();
        }
        /// <summary>
        /// 刷新令牌成功回调
        /// </summary>
        /// <param name="set">token内容</param>
        private void OnRefreshTokenSuccess(TokenSet set) {

            Console.WriteLine("令牌刷新成功:");
            Console.WriteLine("AccessToken: " + set.AccessToken);
            Console.WriteLine("RefreshToken: " + set.RefreshToken);
            Console.WriteLine("IdToken: " + set.IdToken);
            //保存Token
            _tokenManager.SaveToken(set);
            AuthManager.Instance.GetUserInfo(set.AccessToken);
            Console.WriteLine($"登陆状态{AuthManager.Instance.AuthStatus}");
        }

        /// <summary>
        /// 获取用户信息失败回调
        /// </summary>
        /// <param name="obj">失败信息</param>
        private void OnGetUserInfoFailed(string obj) {
            Console.WriteLine("获取用户信息失败:" + obj);
        }
        /// <summary>
        /// 获取用户信息成功回调
        /// </summary>
        /// <param name="set">用户信息</param>
        private void OnGetUserInfoSuccess(UserInfoSet set) {
            Console.WriteLine("获取用户信息成功：");
            userInfoSet = set;
            _tokenManager.SaveLoginMeta(new LoginMeta {
                IsLoggedIn = true,
                UserInfo = set
            });

            // 更新登录状态


            if (SetFrom.setFrom == null) {
                return;
            }
            SetFrom.setFrom.ApplyModifications(
                new UIModification { ControlName = "P_NO_Login", PropertyName = "Visible", Value = false },
                new UIModification { ControlName = "P_Login", PropertyName = "Visible", Value = true },
                new UIModification { ControlName = "L_UserName", PropertyName = "Text", Value = set.name },
                new UIModification { ControlName = "L_Welcome", PropertyName = "Text", Value = $"欢迎回来，{userInfoSet.nickname}！" }
                );


        }
        /// <summary>
        /// 登录成功回调
        /// </summary>
        /// <param name="set"></param>
        private void OnLoginSuccess(TokenSet set) {
            Console.WriteLine("登录成功");
            Console.WriteLine("AccessToken: " + set.AccessToken);
            Console.WriteLine("RefreshToken: " + set.RefreshToken);
            Console.WriteLine("IdToken: " + set.IdToken);
            if (set != null
                && !string.IsNullOrWhiteSpace(set.AccessToken)
                && !string.IsNullOrWhiteSpace(set.RefreshToken)
                && !string.IsNullOrWhiteSpace(set.IdToken)) {
                //保存Token
                _tokenManager.SaveToken(set);
                //获取用户信息
                AuthManager.Instance.GetUserInfo(set.AccessToken);

            } else {
                Console.WriteLine("TokenSet为空");
            }
        }
        private void OnloginFailed(String error) {
            Console.WriteLine("登录失败");
            Console.WriteLine(error);
        }
        private async Task ReLogin() {
            TokenSet? tokenSet = _tokenManager.GetToken();
            if (tokenSet != null && !string.IsNullOrWhiteSpace(tokenSet.RefreshToken)) {
                Console.WriteLine(tokenSet.RefreshToken);
                await AuthManager.Instance.RefreshToken(tokenSet.RefreshToken);
            }

        }
        /// <summary>
        /// 登录状态发生改变回调
        /// </summary>
        /// <param name="status">当前状态</param>
        /// <exception cref="NotImplementedException"></exception>
        private void OnAuthStatusChanged(AuthStatus status) {
            Console.WriteLine($"登录状态回调,当前状态{status}");
            if (status == AuthStatus.Success) {
                AccAssManage.Instance?.UpdateLoginState(new LoginMeta() { 
                    IsLoggedIn = true,
                    UserInfo = null
                });
            }
            if(status == AuthStatus.LoginOut || status == AuthStatus.Failed) {
                AccAssManage.Instance?.UpdateLoginState(new LoginMeta() {
                    IsLoggedIn = false,
                    UserInfo = null
                });
            }

        }
        #endregion

        #region 对外提供的方法
        /// <summary>
        /// 获取用户访问令牌
        /// </summary>
        /// <returns>访问令牌，如果令牌不存在返回空字符串</returns>
        public String? GetAccessToken() {
            var tokenSet = _tokenManager.GetToken();
            if (tokenSet != null) {
                return tokenSet.AccessToken;
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取用户刷新令牌
        /// </summary>
        /// <returns>刷新令牌，如果令牌不存在返回空字符串</returns>
        public String? GetRefreshToken() {
            var tokenSet = _tokenManager.GetToken();
            if (tokenSet != null) {
                return tokenSet.RefreshToken;
            }
            return string.Empty;
        }
        /// <summary>
        /// 获取用户ID令牌
        /// </summary>
        /// <returns>ID令牌</returns>
        public String? GetIdToken() {
            var tokenSet = _tokenManager.GetToken();
            if (tokenSet != null) {
                return tokenSet.IdToken;
            }
            return string.Empty;
        }

        public void StartLogin(Form form) {
            AuthManager.Instance.Login(form);
        }
        public void Logout() {
            AuthManager.Instance.Logout(_tokenManager.GetToken());
        }

        public void RefreshToken() {
            AuthManager.Instance.RefreshToken(_tokenManager.GetToken()?.RefreshToken);
        }
        public void GetUserInfo() {
            AuthManager.Instance.GetUserInfo(_tokenManager.GetToken()?.AccessToken);
        }
        public AuthStatus GetAuthStatus() {
            return AuthManager.Instance.AuthStatus;
        }
        public LoginMeta? GetLoginMeta() {
            return _tokenManager.GetLoginMeta();
        }

        #endregion


    }
}
