using System;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace Plane.Communication
{
    internal class UdpServerConnection : UdpConnectionBase
    {
        private bool _disposed;

        private IOutputStream _outputStream;

        private DataWriter _writer;

        /// <summary>
        /// 初始化 <see cref="UdpServerConnection"/> 的实例，并指定输出流。
        /// </summary>
        /// <param name="outputStream">用于发送数据的输出流。</param>
        public UdpServerConnection(IOutputStream outputStream)
        {
            _outputStream = outputStream;
            _writer = new DataWriter(_outputStream);
        }

        public bool NeedNewOutputStream { get; private set; }

        public override void Close()
        {
            NeedNewOutputStream = false;
            IsOpen = false;
            _outputStream?.Dispose();
            _writer?.Dispose();
            _disposed = true;
        }

        public override Task OpenAsync()
        {
            if (_disposed)
            {
                NeedNewOutputStream = true;
            }
            IsOpen = true;
            return TaskUtils.CompletedTask;
        }

        public void SetOutputStream(IOutputStream outputStream)
        {
            _outputStream?.Dispose();
            _writer?.Dispose();
            _outputStream = outputStream;
            _writer = new DataWriter(_outputStream);
            NeedNewOutputStream = false;
            _disposed = false;
        }

        protected override async Task SendAsync(byte[] datagram, int bytes)
        {
            if (datagram.Length != bytes)
            {
                Array.Resize(ref datagram, bytes);
            }
            try
            {
                _writer.WriteBytes(datagram);
                await _writer.StoreAsync();
            }
            catch (Exception ex)
            {
                Close();
                RaiseExceptionThrown(ex);
            }
        }
    }
}
