using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace FLY.Thick.Base.UI
{
    public class LCUS1 : INotifyPropertyChanged
    {
        public string PortName { get; set; } = "COM6";
        public string ErrMsg { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;
        DispatcherTimer timer;

        public bool IsOn { get; set; }
        private bool enable;
        public bool Enable 
        {
            get {
                return enable;
            }
            set {
                if (enable != value) {
                    enable = value;
                    timer.IsEnabled = enable;
                }
            }
        }
        public LCUS1() {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
        }
        
        private void Timer_Tick(object sender, EventArgs e)
        {
            //每1秒都写状态。 避免通讯不上
            try
            {
                SerialPort serial = new SerialPort();
                serial.PortName = PortName;
                serial.BaudRate = 9600;
                serial.Open();
                byte[] buf;
                if (IsOn) 
                    buf = new byte[] { 0xa0, 0x01, 0x01, 0xa2 };
                else
                    buf = new byte[] { 0xa0, 0x01, 0x00, 0xa1 };

                serial.Write(buf, 0, buf.Length);
                serial.Close();
                string msg = IsOn ? "On" : "Off";
                ErrMsg = $"{DateTime.Now} {msg}";
            }
            catch (Exception _e)
            {
                ErrMsg = _e.Message;
            }
        }

        public void On()
        {
            IsOn = true;
        }
        public void Off()
        {
            IsOn = false;
        }
    }
}