using System.IO.Ports;
using MECF.Framework.Common.Communications;

namespace MECF.Framework.Simulator.Core.Driver
{
    public class SerialPortDeviceSimulator : DeviceSimulator
    {
        #region Variables

        private readonly AsyncSerialPort _serialPort;

        #endregion

        #region Constructors


        public SerialPortDeviceSimulator(string port, int commandIndex, string lineDelimiter, char msgDelimiter,
            bool isAscii = true)
            : base(commandIndex, lineDelimiter, msgDelimiter)
        {
            _serialPort = new AsyncSerialPort(port, 9600, 8, Parity.None, StopBits.One, lineDelimiter, isAscii);
            _serialPort.OnDataChanged += OnReadMessage;
            _serialPort.OnBinaryDataChanged += OnReadMessage;
            _serialPort.OnErrorHappened += OnErrorMessage;


        }

        public SerialPortDeviceSimulator(string port, int commandIndex, string lineDelimiter, char msgDelimiter,
            bool isAscii, int dataBits)
            : base(commandIndex, lineDelimiter, msgDelimiter)
        {
            _serialPort = new AsyncSerialPort(port, 19200, dataBits, Parity.Even, StopBits.One, lineDelimiter, isAscii);
            _serialPort.OnDataChanged += OnReadMessage;
            _serialPort.OnBinaryDataChanged += OnReadMessage;
            _serialPort.OnErrorHappened += OnErrorMessage;
        }

        public SerialPortDeviceSimulator(string port, int commandIndex, string lineDelimiter, char msgDelimiter,
            bool isAscii, string parity)
            : base(commandIndex, lineDelimiter, msgDelimiter)
        {
            _serialPort = new AsyncSerialPort(port, 9600, 8, Parity.Even, StopBits.One, lineDelimiter, isAscii);
            _serialPort.OnDataChanged += OnReadMessage;
            _serialPort.OnBinaryDataChanged += OnReadMessage;
            _serialPort.OnErrorHappened += OnErrorMessage;
        }


        #endregion

        #region Properties

        public override bool IsEnabled => _serialPort != null && _serialPort.IsOpen();

        public override bool IsConnected => IsEnabled;

        public string PortName
        {
            get => _serialPort.PortName;
            set => _serialPort.PortName = value;
        }


        public string RemoteConnection { get; set; }

        #endregion


        #region Methods
        

        public void Enable()
        {
            _serialPort.Open();
        }

        public void Disable()
        {
            _serialPort.Close();
        }

        protected override void ProcessWriteMessage(string msg)
        {
            _serialPort.Write(msg);
        }

        protected override void ProcessWriteMessage(byte[] msg)
        {
            _serialPort.Write(msg);
        }


        #endregion

    }
}

