﻿using System.Collections.Generic;
using System;

namespace ChatSDK
{
	 /**
        * The abstract class for the chat manager.
        */
    public abstract class IChatManager
    {
        /**
        * Deletes a conversation from the local database.
        * 
        * If you set `deleteMessages` to `true`, local historical messages will be deleted with the conversation.
        *
        * @param conversationId     The conversation ID.
        * @param deleteMessages 	Whether to delete local historical messages with the conversation.
        *                           - `true`: Yes.
		*                           - `false`: No.
		*
			* @return 					Whether the conversation is successfully deleted:
		*                           - `true`: Yes. 
		*                           - `false`: No.
        */
        public abstract bool DeleteConversation(string conversationId, bool deleteMessages = true);

        /**
	     * Downloads the message attachment.
	     * 
	     * You can also call this method if the attachment fails to be downloaded automatically.
	     *
	     * @param messageId The ID of the message with the attachment to be downloaded.
	     * @param handle    The download status callback. See {@link CallBack}.
	     */
        public abstract void DownloadAttachment(string messageId, CallBack handle = null);

        /**
	     * Downloads the message thumbnail.
		 * 
	     * You can also call this method if the message thumbnail fails to be downloaded automatically.
		 * 
	     * @param messageId The ID of the message with the thumbnail to be downloaded.
	     * @param handle    The download status callback. See {@link CallBack}.
	     */
        public abstract void DownloadThumbnail(string messageId, CallBack handle = null);

        /**
	     * Gets historical messages of the conversation from the server.
	     * 
	     * Historical messages of a conversation can also be obtained with pagination.
	     *
	     * This is an asynchronous method.
	     *
	     * @param conversationId 		The conversation ID.
	     * @param type 					The conversation type. See {@link ConversationType}.
	     * @param startMessageId 		The starting message ID for the query. 
		 *                              If `null` is passed, the SDK gets messages in the reverse chronological order of when the server received the messages.
	     * @param count 				The number of messages that you expect to get on each page.
	     * @param direction     		The direction in which the message is fetched. MessageSearchDirection can be set with following:
         *                   				- `UP`: fetch messages before the timestamp of the specified message ID;
         *                  				- `DOWN`: fetch messages after the timestamp of the specified message ID.
	     * @param handle				The result callback. Returns the list of obtained messages.
	     */
        public abstract void FetchHistoryMessagesFromServer(string conversationId, ConversationType type = ConversationType.Chat, string startMessageId = null, int count = 20, MessageSearchDirection direction = MessageSearchDirection.UP, ValueCallBack < CursorResult<Message>> handle = null);

        /**
	     * Gets the local conversation object.
	     * 
	     * The SDK wil return `null` if the conversation is not found.
	     *
	     * @param conversationId 	The conversation ID.
	     * @param type              The conversation type. See {@link ConversationType}.
	     * @param createIfNeed      Whether to automatically create a conversation if the conversation is not found. 
	     *                          - `true`: Yes.
	     *                          - `false`: No.
	     * @return 		            The conversation found. Returns `null` if the conversation is not found.
	     */
        public abstract Conversation GetConversation(string conversationId, ConversationType type = ConversationType.Chat, bool createIfNeed = true);

		/**
	     * Gets the local thread conversation object.
	     * 
	     * The SDK wil return `null` if the conversation is not found.
	     *
	     * @param threadId 			The threadId ID.
	     * 
	     * @return 		            The conversation found. Returns `null` if the conversation is not found.
	     */
		public abstract Conversation GetThreadConversation(string threadId);

        /**
	     * Gets the all conversations from the server.
	     * 
	     * An empty list will be returned if no conversation is found.
	     *
	     * @param handle    The list of obtained coversations. See {@link ValueCallBack}.
	     */
        public abstract void GetConversationsFromServer(ValueCallBack<List<Conversation>> handle = null);

        /**
	     * Gets the unread message count.
	     * @return		The count of unread messages.
	     *
	     */
        public abstract int GetUnreadMessageCount();

        /**
	     * Imports messages to the local database.
	     * 
	     * You can only import messages that you sent or received.
	     *
	     * @param messages The messages to be imported.
		 * 
		 * @return Whether messages are successfully imported to the local database.
		 *         - `true`: Yes.
         *         - `false`: No.

	     */
        public abstract bool ImportMessages(List<Message> messages);

        /**
	     * Loads all conversations from the local database into the memory.
		 * 
	     * To accelerate the loading, call this method immediately after the user is logged in.
	     * 
	     * @return      The list of loaded conversations.
	     */
        public abstract List<Conversation> LoadAllConversations();

		/**
	     * Loads a specified message from the local database into the memory.
	     * 
	     * @param messageId		The ID of the message to be loaded.
	     * @return				The loaded message object.
	     */
		public abstract Message LoadMessage(string messageId);

		/**
		 * Marks all local conversations as read.
		 * 
		 *  @return	 Whether all local conversations are marked as read. 
		 *           - `true`: Yes. 
		 *           - `false`: No.
		 */
		public abstract bool MarkAllConversationsAsRead();

		/**
		 * Recalls the message.
		 *
		 * This is an asynchronous method.
		 *
		 * @param message	The ID of the message to be recalled.
		 * @param handle    The recall status callback. See {@link CallBack}.
		 */
		public abstract void RecallMessage(string messageId, CallBack handle = null);

		/**
		 * Resends the message.
		 *
		 * This is an asynchronous method.
		 *
		 * @param message	The ID of the message to be resent.
		 * @param handle    The resending status callback. See {@link CallBack}.
		 * @return			The message that is resent.
		 */
		public abstract Message ResendMessage(string messageId, CallBack handle = null);

		/**
		 * Queries local messages.
		 * 
		 * **Note**
		 * If you want to query a great number of messages, pay attention to the memory consumption. A maximum number of 200 messages can be retrieved each time.
		 *
		 * @param keywords   The keyword for query. The data format is String.
		 * @param timestamp  The Unix timestamp for query, which is in milliseconds.
		 * @param maxCount   The maximum number of messages to retrieve.
		 * @param from       The message source, which is usually a conversation ID.
		 * @param direction	 The query direction. See {@link MessageSearchDirection}.
		 * @return           The list of messages.
		 */
		public abstract List<Message> SearchMsgFromDB(string keywords, long timestamp = 0, int maxCount = 20, string from = null, MessageSearchDirection direction = MessageSearchDirection.UP);

		/**
		 * Sends the conversation read receipt to the server.
		 * After this method is called, the sever will set the message status from unread to read. 
		 * The SDK triggers the {@link IChatManagerDelegate#OnConversationRead(string from, string to)} callback on the message sender's client, notifying that the messages are read. This also applies to multi-device scenarios.
		 *
		 * @param conversationId	The conversation ID.
		 * @param handle			The result callback. See {@link CallBack}.
		 */
		public abstract void SendConversationReadAck(string conversationId, CallBack handle = null);

		/**
		 * Sends a message。
		 * 
		 * This is an asynchronous method.
		 *  
		 * For attachment messages such as voice or image, the SDK will automatically upload the attachment by default. See {@link Options#ServerTransfer}.
		 * 
		 * 
		 * @param msg		 The message object to be sent. Ensure that you set this parameter. 
		 * @param handle	 The result callback. See {@link CallBack}.
		 */
		public abstract void SendMessage(ref Message message, CallBack handle = null);

		/**
		 * Sends the read receipt of a message to the server.
		 * 
		 * After this method is called, the sever will set the message status from unread to read. 
		 *
		 * The SDK triggers the {@link IChatManagerDelegate#OnMessagesRead(List<Message>)} callback on the message sender's client, notifying that the messages are read. This also applies to multi-device scenarios.
		 *
		 * @param messageId		The message ID.
		 * @param handle		The result callback. See{@link CallBack}.
		 */
		public abstract void SendMessageReadAck(string messageId, CallBack handle = null);


        	/**
         	* Sends the group message receipt to the server.
         	*
         	* You can only call the method after setting the following method: {@link Options#RequireAck(boolean)} and {@link Message#IsNeedGroupAck(boolean)}.
         	*
         	* Reference:
         	* To send the one-to-one chat message receipt to server, call {@link #SendMessageReadAck(String)};
         	* To send the conversation receipt to the server, call {@link #SendConversationReadAck(String)}.
         	*
         	* @param messageId     The message ID.
         	* @param ackContent    The ack content information. Developer self-defined command string that can be used for specifying custom action/command.
         	* @param handle		The result callback. See{@link CallBack}.
	 	*/
		public abstract void SendReadAckForGroupMessage(string messageId, string ackContent, CallBack callback = null);

		/**
		 * Updates the local message.
		 * 
		 * After this method is called, messages in both the local memory and local database will be updated.
		 *
		 * @param message	The message object to update.
		 * @return			Whether the local message is successfully updated.	 
		 *                  - `true`: Yes. 
		 *                  - `false`: No.
		 */
		public abstract bool UpdateMessage(Message message);

		/**
		 * Removes messages that are sent and received before the Unix timestamp from the local memory and database.
		 *
		 * @param timeStamp	The starting Unix timestamp for removal.
		 * @param handle	The removal result callback. See {@link CallBack}.
		 */

		public abstract void RemoveMessagesBeforeTimestamp(long timeStamp, CallBack handle = null);

		/**
		 * Deletes the specified conversation and its historical messages from the server.
		 * 
		 * This is an asynchronous method.
		 *
		 * @param conversationId 			The conversation ID.
		 * @param conversationType          The conversation type. See {@link ConversationType}.
		 * @param isDeleteServerMessages 	Whether to delete the historical messages with the conversation.
		 *                                  - `true`: Yes.
		 *                                  - `false`: No.
		 * @param handle					Callback for whether the conversation is deleted. See {@link CallBack}.
		 */
		public abstract void DeleteConversationFromServer(string conversationId, ConversationType conversationType, bool isDeleteServerMessages, CallBack handle = null);


        /**
         * 获取翻译服务支持的语言。
         * @param callBack 完成的回调，详见 {@link #ValueCallBack()}。
         *
         * ~english
         * Fetches all languages what the translate service supports.
         * @param callBack The result callback，see {@link #ValueCallBack()}.
         */
        public abstract void FetchSupportLanguages(ValueCallBack<List<SupportLanguage>> handle = null);

        /**
         * Translates a message.
         * @param message The message object.
         * @param languages The list of the target languages.
         * @param ValuecallBack The result callback，see {@link #ValueCallBack()}.
         */
        public abstract void TranslateMessage(Message message, List<string> targetLanguages, ValueCallBack<Message> handle = null);

        /**
         * Fetches the ack details for group messages from server.
         *
         * Fetches by page.
         *
         * Reference:
         * If you want to send group message receipt, see {@link #SendReadAckForGroupMessage}.
         *
         * This is an asynchronous method.
         *
         * @param msgId			The message ID.
		 * @param groupId		The group ID。
         * @param pageSize		The number of records per page.
         * @param startAckId    The start ID for fetch receipts, can be null. If you set it as null, the SDK will start from the server's latest receipt.
         * @param callBack		The result callback, if successful, the SDK will execute the method {@link ValueCallBack#onSuccess(Object)},
         *                      if the call failed, the SDK will execute the method {@link ValueCallBack#onError(int, String)}.
         */
        public abstract void FetchGroupReadAcks(string messageId, string groupId, int pageSize = 20, string startAckId = null, ValueCallBack<CursorResult<GroupReadAck>> handle = null);

        /**
         * Reports a violation message.
         *
         * @param messageId		The ID of the message to report.
         * @param tag			The report type (For example: involving pornography and terrorism).
         * @param reason		The report Reason.
         *
         * @param callBack The result callback，see {@link #CallBack()}.
         */
        public abstract void ReportMessage(string messageId, string tag, string reason, CallBack handle = null);

        /**
         * Adds a reaction.
         *
         * This is an asynchronous method.
         *
         * @param messageId The message ID.
         * @param reaction  The message reaction.
         * @param callback  The result callback which contains the error information if the method fails.
         */
        public abstract void AddReaction(string messageId, string reaction, CallBack handle = null);

        /**
         * Deletes a reaction.
         *
         * This is an asynchronous method.
         *
         * @param messageId The message ID.
         * @param reaction  The reaction content.
         * @param callback  The result callback which contains the error information if the method fails.
         */

        public abstract void RemoveReaction(string messageId, string reaction, CallBack handle = null);

		 /**
         * Gets the list of Reactions.
         *
         * This is an asynchronous method.
         *
         * @param messageIdList  The message ID.
         * @param chatType       The chat type. Only one-to-one chat ({@link MessageType.Chat} and group chat ({@link MessageType.Group}) are allowed.
         * @param groupId        The group ID, which is invalid only when the chat type is group chat.
         * @param callback       The result callback, which contains the Reaction list under the specified message ID（The user list of EMMessageReaction is the summary data, which only contains the information of the first three users）.
         */

        public abstract void GetReactionList(List<string> messageIdList, MessageType chatType, string groupId, ValueCallBack<Dictionary<string, List<MessageReaction>>> handle = null);

         /**
         * Gets the reaction details.
         *
         * This is an asynchronous method.
         *
         * @param messageId    The message ID.
         * @param reaction     The reaction content.
         * @param cursor       The query cursor.
         * @param pageSize     The number of Reactions you expect to get on each page.
         * @param callback     The result callback, which contains the reaction list obtained from the server and the cursor for the next query. Returns null if all the data is fetched.
         */

        public abstract void GetReactionDetail(string messageId, string reaction, string cursor = null, int pageSize = 20, ValueCallBack<CursorResult<MessageReaction>> handle = null);

		/**
		 * Adds a chat manager listener.
		 *
		 * @param chatManagerDelegate 	The chat manager listener to add. It is inherited from {@link IChatManagerDelegate}.
		 * 
		 */
		public void AddChatManagerDelegate(IChatManagerDelegate chatManagerDelegate)
        {
            if (!CallbackManager.Instance().chatManagerListener.delegater.Contains(chatManagerDelegate))
            {
                CallbackManager.Instance().chatManagerListener.delegater.Add(chatManagerDelegate);
            }
        }

		/**
		 * 移除聊天管理器的监听器。
		 *
		 * @param chatManagerDelegate 	要移除的聊天管理器的监听器，继承自 {@link IChatManagerDelegate}。
		 *
		 * ~english
		 * Removes a chat manager listener.
		 *
		 * @param chatManagerDelegate 	The chat manager listener to remove. It is inherited from {@link IChatManagerDelegate}.
		 * 
		 */
		public void RemoveChatManagerDelegate(IChatManagerDelegate chatManagerDelegate)
        {
            if (CallbackManager.IsQuit()) return;
            if (CallbackManager.Instance().chatManagerListener.delegater.Contains(chatManagerDelegate))
            {
                CallbackManager.Instance().chatManagerListener.delegater.Remove(chatManagerDelegate);
            }
        }

		internal void ClearDelegates()
        {
            CallbackManager.Instance().chatManagerListener.delegater.Clear();
        }

    }
}
