using PlaneGcsSdk.Contract.EhNetUWP;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace PlaneGcsSdk.Contract.DtuClient
{
    partial class EhNetLoginMgr
    {
        #region Fields
        private PLNet _PLNet;
        private LoginState _loginState;
        #endregion

        #region Private Methods
        private void InstanceEhNetObject()
        {
            _PLNet = new PLNet();
        }

        private async Task EhNetStart(string ehNetServerIp, string username, string pwd)
        {
            await _PLNet.Start(ehNetServerIp, username, pwd);
        }

        private bool CheckIfLogined()
        {
            return _loginState == LoginState.LoginOk;
        }

        private void ResetLoginStatus()
        {
            _loginState = LoginState.LoginNoUser;
        }

        private async Task SendCommandToDtuServer(string msg)
        {
            await _PLNet.SendCommand(DtuServerUsername, msg);
        }
        #endregion

        #region Event Handlers
        private void _ehNet_Login(object sender, LoginEventArgs e)
        {
            _loginState = e.LoginState;
            if (_loginState == LoginState.LoginOk)
            {
                NickName = _PLNet.MyNick;
                _loginEnNet.Set();
            }
        }

        //private void _ehNet_ExceptionThrown(object sender, PLNet.UWP.ExceptionThrownEventArgs e)
        //{
        //    RaiseExceptionThrown(e.Exception);
        //}

        private void _ehNet_DiscoveredOneUser(object sender, DiscoveredOneUserEventArgs e)
        {
        }

        private void _ehNet_Disconnect(object sender, EventArgs e)
        {
            _loginState = LoginState.LoginOtherError;
            NickName = null;
        }

        private void _ehNet_CommandArrival(object sender, CommandArrivalEventArgs e)
        {
            AcceptProtocolCommand(e.FriendID, e.CmdMessage);
            Debug.WriteLine(e.CmdMessage);
        }
        #endregion
    }
}
