using CommunityToolkit.Mvvm.Input;
using FObjBase;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// PgAddress.xaml 的交互逻辑
    /// </summary>
    public partial class PgAddress : Page
    {
        PgAddressVm viewModel;
        public PgAddress()
        {
            InitializeComponent();
        }
        [Unity.InjectionMethod]
        public void Init()
        {
            viewModel = new PgAddressVm();
            viewModel.Init();
            this.DataContext = viewModel;
        }
    }
    public class PgAddressVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public List<ConnAddr> ConnAddrs { get; }

        public RelayCommand ApplyCmd { get; }

        FObjServiceClientManager serviceClientManager;

        public PgAddressVm()
        {
            ApplyCmd = new RelayCommand(Apply);
            ConnAddrs = new List<ConnAddr>();

        }

        public void Init()
        {
            serviceClientManager = FObjServiceClientManager.Instance;


            foreach (var ca in serviceClientManager.ConnAddrs)
            {
                ConnAddrs.Add(new ConnAddr() { ConnName = ca.ConnName, Address = ca.Addr });
            };
        }

        private void Apply()
        {
            if (!WdPassword.Authorize("Address"))
                return;

            Regex regex_hostname = new Regex(@"(\S+)\:(\d+)");
            Regex regex_ip = new Regex(@"(\d+)\.(\d+)\.(\d+)\.(\d+)\:(\d+)");
            //检测地址格式
            foreach (var ca in ConnAddrs)
            {
                //把地址的 ： 替换为 :
                ca.Address = ca.Address.Replace("：", ":");
                Match m_hostname = regex_hostname.Match(ca.Address);
                Match m_ip = regex_ip.Match(ca.Address);

                if (!m_hostname.Success)
                {
                    //格式错误
                    FLY.ControlLibrary.Window_WarningTip.Show(
                        "格式错误",
                        $"{ca.ConnName} 地址格式错误！ 正确为 IP地址:端口号 或 域名:端口号 , 请检查");
                    return;
                }

                if (m_ip.Success)
                {
                    //这个IP
                    for (int i = 0; i < 4; i++)
                    {
                        if (!int.TryParse(m_ip.Groups[1 + i].Value, out int num))
                        {
                            //格式错误
                            FLY.ControlLibrary.Window_WarningTip.Show(
                                "格式错误",
                                $"{ca.ConnName} 地址格式错误！ 第{i + 1} 位IP段 出错");
                            return;
                        }
                        if (num < 0 || num > 255)
                        {
                            //格式错误
                            FLY.ControlLibrary.Window_WarningTip.Show(
                                "格式错误",
                                $"{ca.ConnName} 地址格式错误！ 第{i + 1}位IP段应该在 0~255 之间");
                            return;
                        }
                    }
                }



                {
                    if (!int.TryParse(m_hostname.Groups[2].Value, out int port))
                    {
                        //格式错误
                        FLY.ControlLibrary.Window_WarningTip.Show(
                            "格式错误",
                            $"{ca.ConnName} 地址格式错误！ 端口出错");
                        return;
                    }
                    if (port < 1 || port > 65535)
                    {
                        //格式错误
                        FLY.ControlLibrary.Window_WarningTip.Show(
                            "格式错误",
                            $"{ca.ConnName} 地址格式错误！ 端口应该在 1~65535 之间");
                        return;
                    }
                }

                var ep = Misc.StringConverter.ToIPEndPoint(ca.Address);
                if (ep == null)
                {
                    //不能转为ep
                    FLY.ControlLibrary.Window_WarningTip.Show(
                        "地址出错",
                        $"{ca.ConnName} 不能有效转换IPv4");
                    return;
                }
            }

            int modifyCnt = 0;
            //检查完毕
            foreach (var ca in ConnAddrs)
            {
                var objCa = serviceClientManager.ConnAddrs.Find(_ca => _ca.ConnName == ca.ConnName);
                if (objCa == null)
                    continue;
                if (objCa.Addr != ca.Address)
                {
                    modifyCnt++;
                    //重新连接
                    serviceClientManager.ReConnect(ca.ConnName, ca.Address);
                }
            };

            if (modifyCnt > 0)
            {
                serviceClientManager.Save();

                FLY.ControlLibrary.Window_Tip.ShowShortTime(
                    "修改成功",
                    $"{modifyCnt}个地址被修改，保存成功");
                return;
            }
            else
            {
                FLY.ControlLibrary.Window_Tip.ShowShortTime(
                    "通知",
                    $"没有任何地址被修改");
                return;
            }
        }
    }
    public class ConnAddr : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// 连接器名称
        /// </summary>
        public string ConnName { get; set; }

        /// <summary>
        /// 设备地址
        /// </summary>
        public string Address { get; set; }

    }
}
