﻿using System.Threading.Tasks;

#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE || UNITY_EDITOR
using UnityEngine;
#endif

namespace ChatSDK
{
    /**
     * The SDK client class, the entry of the chat SDK, defines how to log in to and log out of the chat app and how to manage the connection between the SDK and the chat server.
     */
    public class SDKClient
    {
        private Options _Options;
        private static SDKClient _instance;
        private IClient _Sdk;

        public static SDKClient Instance
        {
            get
            {
                return _instance ?? (_instance = new SDKClient());
            }
        }

        public static bool IsInit { get; internal set; }

        /**
         * The chat manager instance.
         */
        public IChatManager ChatManager { get => _Sdk.ChatManager(); }

        /**
         * The contact manager instance.
         */
        public IContactManager ContactManager { get => _Sdk.ContactManager(); }

        /**
         * The group manager instance.
         */
        public IGroupManager GroupManager { get => _Sdk.GroupManager(); }

        /**
         * The chat room manager instance.
         */
        public IRoomManager RoomManager { get => _Sdk.RoomManager(); }

      

        /**
         * The conversation manager instance.
         */
        internal IConversationManager ConversationManager { get => _Sdk.ConversationManager(); }

        internal IMessageManager MessageManager { get => _Sdk.MessageManager();  }

        /**
         * The user information manager instance.
         */
        public IUserInfoManager UserInfoManager { get => _Sdk.UserInfoManager(); }

        /**
         * The presence manager instance.
         */
        public IPresenceManager PresenceManager { get => _Sdk.PresenceManager(); }

        /**
         * The thread manager instance.
         */	
		public IChatThreadManager ThreadManager { get => _Sdk.ThreadManager(); }
        /**
         * The SDK options.
         */
        public Options Options { get { return _Options; } }

        /**
         * The SDK version.
         */
        public string SdkVersion { get => "1.0.5"; }


        /**
         * The ID of the current login user.
         */
        public string CurrentUsername { get => _Sdk.CurrentUsername(); }

        /**
         * Whether the current user is logged into the chat app.
         * - `true`: Yes.
         * - `false`: No. The current user is not logged into the chat app yet.
         */
        public bool IsLoggedIn { get => _Sdk.IsLoggedIn(); }

        /**
         * Whether the SDK is connected to the server.
         * - `true`: Yes.
         * - `false`: No.

         */
        public bool IsConnected { get => _Sdk.IsConnected(); }

        /**
         * The token of the current user.
         */
        public string AccessToken { get => _Sdk.AccessToken(); }

        /**
		 * Adds a connection listener.
		 *
		 * @param connectionDelegate 		The connection listener to add. It is inherited from {@link IConnectionDelegate}.
		 * 
		 */
        public void AddConnectionDelegate(IConnectionDelegate connectionDelegate)
        {
            if (!CallbackManager.Instance().connectionListener.delegater.Contains(connectionDelegate)) {
                CallbackManager.Instance().connectionListener.delegater.Add(connectionDelegate);
            }
        }

        /**
		 * Removes a connection listener.
		 *
		 * @param connectionDelegate 		The connection listener to remove. It is inherited from {@link IConnectionDelegate}.
		 * 
		 */
        public void DeleteConnectionDelegate(IConnectionDelegate connectionDelegate)
        {
            if (CallbackManager.IsQuit()) return;
            if (CallbackManager.Instance().connectionListener.delegater.Contains(connectionDelegate))
            {
                CallbackManager.Instance().connectionListener.delegater.Remove(connectionDelegate);
            }
        }

        /**
		 * Adds a connection listener.
		 *
		 * @param multiDeviceDelegate 		The multi-device listener to add. It is inherited from {@link IMultiDeviceDelegate}.
		 * 
		 */

        public void AddMultiDeviceDelegate(IMultiDeviceDelegate multiDeviceDelegate)
        {
            if (!CallbackManager.Instance().multiDeviceListener.delegater.Contains(multiDeviceDelegate))
            {
                CallbackManager.Instance().multiDeviceListener.delegater.Add(multiDeviceDelegate);
            }
        }

        /**
		 * Removes a connection listener.
		 *
		 * @param multiDeviceDelegate 		The multi-device listener to remove. It is inherited from {@link IMultiDeviceDelegate}.
		 * 
		 */
        public void DeleteMultiDeviceDelegate(IMultiDeviceDelegate multiDeviceDelegate)
        {
            if (CallbackManager.IsQuit()) return;
            if (CallbackManager.Instance().multiDeviceListener.delegater.Contains(multiDeviceDelegate))
            {
                CallbackManager.Instance().multiDeviceListener.delegater.Remove(multiDeviceDelegate);
            }
        }
        /**
        * Initializes the SDK.
        * 
        * Make sure that the SDK initialization is complete before you call any methods.
        *
        * @param options The options for SDK initialization. Ensure that you set the options. See {@link Options}.
        */
        public void InitWithOptions(Options options)
        {
            CallbackManager.Instance();
            _Options = options;
            _Sdk.InitWithOptions(options);
            registerManagers();
        }

        /**
         * Creates a new user.
         *
         * This is an asynchronous method.
         *
         * @param username The user ID. Ensure that you set this parameter. 
         * 
         * The user ID can contain a maximum of 64 characters of the following types:
         * - 26 lowercase English letters (a-z);
         * - 26 uppercase English letters (A-Z);
         * - 10 numbers (0-9);
         * - "_", "-", "."
         * 
         * The user ID is case-insensitive, so Aa and aa are the same user ID. 
         * 
         * The email address or the UUID of the user cannot be used as the user ID.
         * 
         * You can also set the user ID using a regular expression in the format of ^[a-zA-Z0-9_-]+$. 
         * 
         * @param password The password. The password can contain a maximum of 64 characters. Ensure that you set this parameter.
         * @param handle  The creation result callback. See {@link CallBack}.          
         *             
         */
        public void CreateAccount(string username, string password, CallBack handle = null)
        {
            _Sdk.CreateAccount(username, password, handle);
        }

        /**
         * Logs in to the chat server with a password or an Easemob token.
         * 
         * This is an asynchronous method.
         *
         * @param username 		The user ID. Ensure that you set this parameter.
         * @param pwdOrToken 	The password or token. Ensure that you set this parameter.
         * @param isToken       Whether to log in with a token or a password. 
         *                      - `true`：A token is used.
         *                      - (Default) `false`：A password is used.
         * @param handle 	    The login result callback. See {@link CallBack}.
         *
         */
        public void Login(string username, string pwdOrToken, bool isToken = false, CallBack handle = null)
        {
            _Sdk.Login(username, pwdOrToken, isToken, handle);
        }

        /**
         * Logs in to the chat server with the user ID and an Agora token.
         * 
         * You can also log in to the chat server with the user ID and a password. See {@link #Login(string, string, bool, CallBack)}.
         *
         * This an asynchronous method.
         *
         * @param username      The user ID. Ensure that you set this parameter.
         * @param token         The Agora token. Ensure that you set this parameter.
         * @param handle        The login result callback. See {@link CallBack}.
         *
         */
        public void LoginWithAgoraToken(string username, string token, CallBack handle = null)
        {
            _Sdk.LoginWithAgoraToken(username, token, handle);
        }

        /**
         * Renews the Agora token.
         * 
         * If you log in with an Agora token and are notified by a callback method {@link IConnectionDelegate} that the token is to be expired, you can call this method to update the token to avoid unknown issues caused by an invalid token.
         *
         * @param token The new Agora token.
         */
        public void RenewAgoraToken(string token)
        {
            _Sdk.RenewAgoraToken(token);
        }

        /**
         * Logs out of the chat app.
         *
         * This is an asynchronous method.
         *
         * @param unbindToken Whether to unbind the token upon logout. This parameter is available only to mobile platforms.
         *                    - `true`: Yes.
         *                    - `false`: No.
         *                    
         * @param handle 	    The logout result callback. see {@link CallBack}.
         * 
         */
        public void Logout(bool unbindDeviceToken, CallBack handle = null)
        {
            _Sdk.Logout(unbindDeviceToken, new CallBack(
                onSuccess: () => {
                    CallbackManager.Instance().CleanAllCallback();
                    handle?.Success?.Invoke();
                },
                onError:(code, desc) => {
                    handle?.Error?.Invoke(code, desc);
                }
                ));
        }

        private SDKClient()
        {
            _Sdk = IClient.Instance;
            IsInit = true;
        }

        private void registerManagers() {
            _Sdk.ContactManager();
            _Sdk.ChatManager();
            _Sdk.GroupManager();
            _Sdk.RoomManager();
            _Sdk.ConversationManager();
            _Sdk.UserInfoManager();
            _Sdk.PresenceManager();
            _Sdk.ThreadManager();
        }
    }
}





