using System;
using System.IO.Ports;
using System.Text;
using System.Threading;

namespace ShanghaiEnvironmentalTechnology
{
    public class RS485Communicator
    {
        private SerialPort _serialPort;
        private bool _isListening;

        public event Action<string> DataReceived;

        public RS485Communicator(string portName, int baudRate = 19200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits)
            {
                ReadTimeout = 500,
                WriteTimeout = 500
            };

            _serialPort.DataReceived += SerialPort_DataReceived;
        }

        public void Open()
        {
            if (!_serialPort.IsOpen)
            {
                _serialPort.Open();
                _isListening = true;
            }
        }

        public void Close()
        {
            if (_serialPort.IsOpen)
            {
                _isListening = false;
                _serialPort.Close();
            }
        }

        public void SendData(string data)
        {
            if (_serialPort.IsOpen)
            {
                byte[] bytesToSend = Encoding.ASCII.GetBytes(data);
                _serialPort.Write(bytesToSend, 0, bytesToSend.Length);
            }
            else
            {
                throw new InvalidOperationException("Serial port is not open.");
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (_isListening && _serialPort.IsOpen)
            {
                string receivedData = _serialPort.ReadLine();
                DataReceived?.Invoke(receivedData);
            }
        }
    }
}
