using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IMLibrary.Security; 
using IMLibrary.WS; 
using IMLibrary.WS.Server;
using IMLibrary.WS.Net;
using IMLibrary.BinaryPacket;
using IMLibrary.Server;

using P;
using Ourmsg.Factory;
using Ourmsg.Enum;

namespace Ourmsg.Server
{ 
    #region 用户注册服务
    /// <summary>
    /// 用户注册服务
    /// </summary>
    public class RegisterUserServer  :WebSocketService 
    { 
        public RegisterUserServer()
        {
            Path = "/RegisterUser";
        }

        public override void OnClose(WebSocketSession session, CloseEventArgs e)
        {

        }

        public override void OnOpen(WebSocketSession session)
        {
            Console.WriteLine(session.ID + ":is Connection!");
        }

        public override void OnError(WebSocketSession session, ErrorEventArgs e)
        {
            Console.WriteLine("error:" + e.Message);
        }

        private   void CloseSession(string ID)
        {
            Sessions.CloseSession(ID);//强行关闭连接
        }

        public override void OnMessage(WebSocketSession session, MessageEventArgs e)
        {
            if (e.RawData.Length <  BinaryMsg.HeaderLength) return;
            var p = new  BinaryMsg(e.RawData);

            #region 注册新用户
            if (p.CommandType == (byte)CommandType.UserRegister)
            {
                #region 解密解压
                if (p.Encrypt)//先解密
                {
                    p.Payload = Encryption.Decrypt3DES(p.Payload);
                }
                if (p.Compress)//再解压
                {
                    p.Payload = IMLibrary.GZip.Stream.Decompress(p.Payload);
                }
                #endregion

                UserRegister ur = XML.ConvertToObject(p.GetPayloadString()) as UserRegister;
                if (ur == null)
                {
                    CloseSession(session.ID);//断开客户端连接
                    return;
                }
                else
                {
                    if (ur.UserName == null || ur.UserName == string.Empty)
                    {
                        CloseSession(session.ID);//断开客户端连接
                        return;
                    }

                    var userID = CacheRegisterUser.GetUnusedID();
                    if (userID == 0) return;
                    ur.UserID = userID;
                    var insertCount = DBO.RegisterUser(ur);
                    if (insertCount > 0)
                    {
                        ur.Password =null;
                        p.Compress = false;
                        p.Encrypt = false;
                        p.Payload = XML.ConvertToArray(ur);
                        p.Payload = Encryption.Encrypt3DES(p.Payload);
                        p.Encrypt = true;
                        Sessions.SendTo(p.ToArray(), session.ID);
                    } 
                }
            }
            #endregion

            System.Threading.Thread.Sleep(2000);
            CloseSession(session.ID);//断开客户端连接 
        }

        #region 服务功能
        public void Start(int port)
        { 
            if (WSServer == null)
            {
                WSServer = new WebSocketServer(port);
                WSServer.KeepClean = true;
                WSServer.AddWebSocketService<WebSocketSession>(Path , () => new  WebSocketSession(this)); //
                WSServer.AuthenticationSchemes = AuthenticationSchemes.Basic;
                WSServer.Realm = "OurMsg Server";
                WSServer.UserCredentialsFinder = ID =>
                {
                    var name = ID.Name;
                    // Return user name, password, and roles.If the user credentials aren't found,null.
                    return name == "liggyi" ? new NetworkCredential(name, "liggyi@Ourmsg.net") : null;
                };
                WSServer.Start();
            }
        }

        public void Stop()
        {
            if (WSServer != null)
            {
                WSServer.Stop();
                WSServer = null;
            } 
        }
        #endregion 
    }
    #endregion

}
