using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SingleDevice.Helper
{
    /// <summary>
    /// 地址转换类
    /// </summary>
    internal static class ExtensionMethod
    {
        /// <summary>
        /// Modbus 地址转换
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static string ToModbusAdd(this string address)
        {
            if (address == null) return "";
            if (address.Length > 0)
            {
                address = address.Trim();
                if (address.ToUpper().Contains("GM") && address.Length >= 3)
                {
                    var res = address.Remove(0, 2);
                    if (res != null && res.Length > 0) return (int.Parse(res) + 4096).ToString();
                }
                else if (address.ToUpper().Contains("M") && address.Length >= 4)
                {
                    var res = address.Substring(1).Split('.');
                    if (res != null && res.Length == 2)
                    {
                        if (int.TryParse(res[0], out int firstAddress) && int.TryParse(res[1], out int ExitAddress))
                        {
                            if (ExitAddress >= 0 && ExitAddress <= 7)
                            {
                                return ((firstAddress * 8) + 320 + ExitAddress).ToString();
                            }
                        }
                    }
                }
                else if (address.ToUpper().Contains("GI") && address.Length >= 3)
                {
                    var res = address.Remove(0, 2);
                    if (res != null && res.Length > 0) return res;
                }
                else if (address.ToUpper().Contains("LB") && address.Length >= 3)
                {
                    var res = address.Substring(2);
                    if (res != null && res.Length > 0)
                    {
                        if (int.TryParse(res, out int firstAddress)) return firstAddress.ToString();
                    }
                }
                else if ((address.ToUpper().Contains("VW") || address.ToUpper().Contains("VD")) && address.Length >= 3)
                {
                    var res = address.Substring(2);
                    if (res != null && int.TryParse(res, out int tempAddress))
                    {
                        return ((tempAddress / 2) + 100).ToString();
                    }
                }
                else if (address.ToUpper().Contains("LW") && address.Length >= 3)
                {
                    var res = address.Substring(2);
                    if (res != null && int.TryParse(res, out int LwAddress))
                    {
                        return LwAddress.ToString();
                    }
                }
            }
            return "";
        }


    }
}
