using FObjBase;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

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 = new Regex(@"(\d+)\.(\d+)\.(\d+)\.(\d+)\:(\d+)");
            //检测地址格式
            foreach(var ca in ConnAddrs) 
            {
                Match m = regex.Match(ca.Address);
                if (!m.Success) 
                {
                    //格式错误
                    FLY.ControlLibrary.Window_WarningTip.Show(
                        "格式错误",
                        $"{ca.ConnName} 地址格式错误！ 正确为 IP地址:端口号, 请检查");
                    return;
                }
                for (int i = 0; i < 4; i++)
                {
                    if (!int.TryParse(m.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.Groups[5].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;
                    }
                }
            }

            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; }

    }
}
