#if !NETFX_CORE

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Plane.Communication
{
    public partial class UdpThroughDtuServiceConnection
    {
        private UdpClient _client;

        /// <summary>
        /// 初始化 <see cref="UdpServerConnection"/> 的实例，并指定远程终结点和发送数据所使用的方法。
        /// </summary>
        public UdpThroughDtuServiceConnection(string ip, int port)
        {
            DtuServiceIP = ip;
            DtuServicePort = port;
            _client = new UdpClient();
        }

        /// <summary>
        /// 登陆到Dtu服务端。
        /// 登陆方式极其简单，只需发送一个数据包（内含希望连接到的飞机ID）
        /// </summary>
        /// <returns></returns>
        public virtual async Task OpenAsync()
        {
            if (!string.IsNullOrEmpty(CopterIDToBind))
            {
                _client.Connect(IPAddress.Parse(DtuServiceIP), DtuServicePort);
                var bytes = ConstructHandShakeDatagramToDTUService();
                await _client.SendAsync(bytes, bytes.Length);

                //等待服务端的应答，获取是否连接成功飞机的结果
                var result = await _client.ReceiveAsync();
                var ret = AnalyzeHandShakeDatagramFromDTUService(result.Buffer);
                if (ret == DTUHandShakeResult.Successful)
                {
                    IsOpen = true;
                }
                else if (ret == DTUHandShakeResult.Occupied)
                {
                    throw new Exception("飞机已被占用！");
                }
                else if (ret == DTUHandShakeResult.NotExisted)
                {
                    throw new Exception("飞机不存在！");
                }
            }
        }

        public virtual void Close()
        {
            IsOpen = false;
            _client.Close();
        }

        private async Task SendAsync(byte[] datagram, int bytes)
        {
            try
            {
                await _client.SendAsync(datagram, bytes).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Close();
                RaiseExceptionThrown(ex);
            }
        }
    }
}

#endif