using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using STSdb4.Database;

namespace Ourmsg.Server
{
    /// <summary>
    /// 离线消息存取客户端
    /// </summary>
    public class OfflineMessageClient
    {
        /// <summary>
        /// 连接引擎
        /// </summary>
       IStorageEngine engine=null ;

        #region 保存离线消息
        /// <summary>
        ///  
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="msgData"></param>
        public void SaveOfflineMsg(UInt32 userID, byte[] msgData)
        {
            if (engine == null) return;
            ITable<long, byte[]> table = engine.OpenXTable<long, byte[]>("OfflineMessage" + userID);
            var id = System.DateTime.Now.Ticks;
            table[id] = msgData;
            engine.Commit();
        }
        #endregion

        #region 获得用户离线消息
        /// <summary>
        ///  
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="msgData"></param>
        public KeyValuePair<long, byte[]>[] GetOfflineMessages(UInt32 userID)
        {
            if (engine == null) return null;
            ITable<long, byte[]> table = engine.OpenXTable<long, byte[]>("OfflineMessage" + userID);
            var msgs= table.ToArray();
            table.Clear();
            engine.Commit();
            return msgs;
        }
        #endregion

        #region 打开连接
        /// <summary>
        /// 打开连接
        /// </summary>
        /// <param name="hostIP"></param>
        /// <param name="prot"></param>
        public void OpenConnection(string hostIP = "localhost", int prot = 2005)
        {
            if (engine == null)
                engine = STSdb.FromNetwork(hostIP, prot);//"127.0.0.1"
        }
        #endregion

        #region 关闭连接
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void CloseConnection()
        {
            if (engine != null)
            {
                engine.Commit();
                engine.Close();
            }
        }
        #endregion

    }
}
