using Plane.Communication;
using System.Text;
using System.Threading.Tasks;

namespace PlaneGcsSdk.Contract.DtuClient
{
    /// <summary>
    /// 基于PLNet的用户登录体系的Udp连接实体类。
    /// <para>具体登陆流程：1，利用用户名和密码登陆PLNet，获取随机码；2，利用随机码登陆Dtu透传服务器；</para>
    /// </summary>
    public partial class BasedOnEhNetUdpDtuServiceConnection : UdpThroughDtuServiceConnection
    {
        #region Fields
        public int _randCode;
        #endregion

        #region Properties
        
        #endregion

        /// <summary>
        /// 基于PLNet的用户登录体系的Udp连接实体类。
        /// <para>具体登陆流程：1，利用用户名和密码登陆PLNet，获取随机码；2，利用随机码登陆Dtu透传服务器；</para>
        /// </summary>
        /// <param name="dtuServiceIp"></param>
        /// <param name="dtuServicePort"></param>
        /// <param name="randCode">用户随机数</param>
        public BasedOnEhNetUdpDtuServiceConnection(string dtuServiceIp, int dtuServicePort, int randCode) 
            : base(dtuServiceIp, dtuServicePort)
        {
            FLAG_DTU_HANDSHAKE_HEAD = "ehnetrnd";
            _randCode = randCode;
        }

        protected override byte[] ConstructHandShakeDatagramToDTUService()
        {
            return Encoding.ASCII.GetBytes($"{FLAG_DTU_HANDSHAKE_HEAD}{_randCode}");
        }

        /// <summary>
        /// 分析由DTU服务端返回的握手包
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        protected override DTUHandShakeResult AnalyzeHandShakeDatagramFromDTUService(byte[] buffer)
        {
            var strResult = Encoding.ASCII.GetString(buffer);//返回的格式为“ehnetrndxxxx”
            if (strResult.StartsWith(FLAG_DTU_HANDSHAKE_HEAD))
            {
                return DTUHandShakeResult.Successful;
            }
            return DTUHandShakeResult.Unknown;
        }

        public override async Task<int> ReadAsync(byte[] buffer, int offset, int count)
        {
            var iRet = await base.ReadAsync(buffer, offset, count);
            //解密数据
            buffer.DecryptByKey((byte)(_randCode % byte.MaxValue), offset, count);
            return iRet;
        }

        public override Task WriteAsync(byte[] buffer, int offset, int count)
        {
            //加密数据
            buffer.EncryptByKey((byte)(_randCode % byte.MaxValue), offset, count);
            var iRet = base.WriteAsync(buffer, offset, count);
            return iRet;
        }
    }
}
