using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace ProductionControl.Device
{
    public class HeightDev:IDisposable
    {
        //public double HeightValue { private set; get; } 

        public Action<WarningEnum, string> WarningEvent;
        /// <summary>
        /// 值<值>
        /// </summary>
        public Action<double> HeightEvent;
        /// <summary>
        /// 是否打开设备成功
        /// </summary>
        public bool IsInit { get; private set; } = false;
        private System.Timers.Timer timer = new System.Timers.Timer();
        private Socket socketObj;
        private double decimalNum=-1;

        private bool _isDebug = false;
        public HeightDev(bool isDebug)
        {
            _isDebug = isDebug;
        }
        public HeightDev()
        {
        }
        public bool start(string net_ip, int net_port)
        {
            try
            {
                // 1、创建socket对象
                socketObj = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 2、字符串ip转网络ip， 端口号转int
                IPAddress ip = IPAddress.Parse(net_ip);
                int port = Convert.ToInt32(net_port);
                // 3、连接服务器
                socketObj.Connect(ip, port);

                IsInit = true;
                if (_isDebug)
                {
                    timer.Elapsed += Timer_Elapsed;
                    timer.Interval = 500;
                    timer.Start();
                }
                return true;
            }
            catch (Exception ex)
            {
                WarningEvent?.Invoke(WarningEnum.High,ex.Message);
                return false;
            }
        }
        public void stop()
        {
            if (!IsInit) return;

            //关闭客户端 
            try
            {
                IsInit = false;
                if (_isDebug)
                {
                    timer.Elapsed -= Timer_Elapsed;
                    timer.Stop();
                }
                socketObj.Close();
            }
            catch { }
        }
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!IsInit) return;

            timer.Stop();
            getHeight();
            timer.Start();
        }
        public double getHeight()
        {
            try
            {
                if (!IsInit) return -1;
                if (decimalNum == -1)
                {
                    decimalNum = getDecimal();
                    if (decimalNum < 0)
                        throw new Exception("HeightDev start Err!");
                }
                // 发送消息  
                socketObj.Send(Encoding.Default.GetBytes("SR,01,037\r\n"));

                // 接收消息 
                byte[] buffer = new byte[1024];
                socketObj.Receive(buffer);
                string res = System.Text.Encoding.Default.GetString(buffer);
                if (res.IndexOf("SR,01,037,") != 0)
                    return -1;
                res = res.Replace("SR,01,037,", "");
                double val;
                if (decimalNum < 1)
                    val = Convert.ToDouble(res);
                else
                    val = Convert.ToDouble(res) / decimalNum;

                val = Math.Abs(val) * 1000;
                HeightEvent?.Invoke(val);
                return val;
            }
            catch(Exception ex)
            {
                WarningEvent?.Invoke(WarningEnum.Low, ex.Message);
                return -1;
            }
        }
        private double getDecimal()
        {
            if (!IsInit) return -1;

            // 发送消息  
            socketObj.Send(Encoding.Default.GetBytes("FR,01,037\r\n"));

            // 接收消息 
            byte[] buffer = new byte[1024];
            socketObj.Receive(buffer);
            string res = System.Text.Encoding.Default.GetString(buffer).Split(new string[] { "\r\n" }, StringSplitOptions.None)[0];
            if (res.IndexOf("FR,01,037,") != 0)
                return -1;
            res= res.Replace("FR,01,037,","");
            return Math.Pow(10,Convert.ToInt32(res));
        }
        public bool reset()
        {
            if (!IsInit) return false;

            // 发送消息  
            socketObj.Send(Encoding.Default.GetBytes("SW,01,001,+000000001\r\n"));

            // 接收消息 
            byte[] buffer = new byte[1024];
            socketObj.Receive(buffer);
            string res = System.Text.Encoding.Default.GetString(buffer).Split(new string[] { "\r\n" }, StringSplitOptions.None)[0];
            return res == "SW,01,001";
        }

        public void Dispose()
        {
            stop();
        }
    }
}
