using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using XiaoZhiSharp.Kernels;
using OperatingSystem = XiaoZhiSharp.Kernels.OperatingSystem;

namespace XiaoZhiSharp.Utils.Com
{
    public static class ComUtil
    {
        private static readonly string WinComPrefix = "COM";
        private static readonly string LinuxUsbComPrefix = "/dev/ttyUSB";//USB串口
        private static readonly string LinuxSysComPrefix = "/dev/ttyS";//PC上的串口一般是ttyS；板子上Linux的串口一般叫做ttySAC

        public static List<LinuxCom> LinuxComList { set; get; } = new List<LinuxCom>();

        public static string[] GetLocalComs()
        {
            return SerialPort.GetPortNames();
        }

        public static string PortToString(int port)
        {
            string prefix = string.Empty;
            OperatingSystemType plat = OperatingSystem.GetOperatingSystemType();
            if (plat == OperatingSystemType.Windows)
            {
                prefix = WinComPrefix;
            }
            else if (plat == OperatingSystemType.Linux)
            {
                prefix = LinuxSysComPrefix;
                LinuxCom linuxCom = LinuxComList.FirstOrDefault(l => l.LinuxPort == port);
                if (linuxCom != null)
                {
                    if (linuxCom.LinuxComType == LinuxComType.Usb)
                    {
                        prefix = LinuxUsbComPrefix;
                    }
                    else if (linuxCom.LinuxComType == LinuxComType.System)
                    {
                        prefix = LinuxSysComPrefix;
                    }
                }
            }
            return string.Format("{0}{1}", prefix, port.ToString());
        }

        public static int PortToInt(string portString)
        {
            string prefix = string.Empty;
            OperatingSystemType plat = OperatingSystem.GetOperatingSystemType();
            if (plat == OperatingSystemType.Windows)
            {
                prefix = WinComPrefix;
            }
            else if (plat == OperatingSystemType.Linux)
            {
                prefix = LinuxSysComPrefix;
                LinuxCom linuxCom = LinuxComList.FirstOrDefault(l => portString.Contains(l.LinuxPort.ToString()));
                if (linuxCom != null)
                {
                    if (linuxCom.LinuxComType == LinuxComType.Usb)
                    {
                        prefix = LinuxUsbComPrefix;
                    }
                    else if (linuxCom.LinuxComType == LinuxComType.System)
                    {
                        prefix = LinuxSysComPrefix;
                    }
                }
            }
            if (prefix.Length <= 0)
            {
                throw new IndexOutOfRangeException("串口字符串无法转换");
            }
            return int.Parse(portString.Substring(prefix.Length));
        }
    }
}
