using MegaRobo.Connections.Sockets.Tcp;
using MegaRobo.Contract;
using MegaRobo.ControlDevices.Abstractions;
using MegaRobo.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MegaRobo.C00225155.ControlDevices.Scanner
{
    public abstract class ScannerCodeOfTcpClientBase : ScannerCodeBase<MegaTcpClient>
    {
        public override async Task<string> Initialize(ICoreService coreService, params object[] args)
        {
            try
            {
                this.CoreService = coreService;
                switch (args.Length)
                {
                    case >= 1 when args[0] is IPEndPoint remoteHost:
                        this.ConnectorAdapter = new MegaTcpClient { Logger = coreService.Logger, Name = this.Name };
                        if (this.ConnectorAdapter != null)
                        {
                            this.ConnectorAdapter.DataReceived += this.ConnectorOnDataReceived;
                        }
                        this.ConnectionState = await this.ConnectorAdapter.ConnectAsync(remoteHost);
                        break;
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                this.Logger.LogException(ex);
                return ex.Message;
            }
        }

        private void ConnectorOnDataReceived(object sender, TcpMessage e)
        {
            var msg = e.ParseStirng();
            if (string.IsNullOrEmpty(msg)) return;
            this.Logger.LogInformation($"接收到扫码枪{this.Name}数据:{msg}");
            this.OnDataReceived(this, e);
        }

        public override async Task<string> ReadAsnyc(TimeSpan timeout)
        {
            try
            {
                this.Stop();
                await Task.Delay(20);
                byte[] sendBytes = this.ConnectorAdapter.StringEncoder.GetBytes(this.StartCommandLine);
                var tcpMessage = await this.ConnectorAdapter.WriteAndGetReplyAsync(sendBytes, timeout);
                if (tcpMessage is null)
                {
                    return null;
                }
                    
                this.Code = this.ParseMessage(tcpMessage.ParseStirng(), tcpMessage.Data).TrimEnd();
                this.Stop();
                this.OnScannedEvent(this.Code);
                return this.Code;
            }
            catch (Exception ex)
            {
                this.Logger.LogException(ex);
            }
            return null;
        }
    }
}
