using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WjwLib.API.System;

namespace GatewayTool
{
    public partial class FormPing : FormBase
    {
        public string DomainText 
        {
            get => chkDomain.Text;
            set => chkDomain.Text = value;
        }

        public FormPing()
        {
            InitializeComponent();
            this.IsMinimizable = false;
            this.Title = "Ping";
            this.ShowInTaskbar = false;
            this.pictureBox1.Image = imageList1.Images["Grey"];
        }

        private void ShowInfo(string info)
        {
            this.Invoke((EventHandler)delegate
            {
                rtResult.AppendText(info);
                rtResult.AppendText(System.Environment.NewLine);
                rtResult.ScrollToCaret();
            });
        }

        private long TimeSecondDif(DateTime tim)
        {
            return (DateTime.Now.Ticks - tim.Ticks) / 10000000;
        }

        private async void PingAsync(string ip, int sec)
        {
            DateTime time = DateTime.Now;
            string info = string.Empty;
            int cnt = 0;
            await Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(50);
                        if (TimeSecondDif(time) > sec)
                        {
                            time = DateTime.Now;
                            DateTime dt = DateTime.Now;
                            cnt += 1;
                            PingReply reply = new Ping().Send(ip, 1000);
                            if (reply.Status == IPStatus.Success)
                            {
                                info = $"{DateTime.Now}：来自 {reply.Address} 的回复：字节={reply.Buffer.Length} 时间={reply.RoundtripTime}ms TTL={reply.Options.Ttl}";
                                this.pictureBox1.Image = imageList1.Images["Green"];
                            }
                            else if (reply.Status == IPStatus.DestinationHostUnreachable)
                            {
                                info = $"{DateTime.Now}：来自 {NetworkUtility.GetLocalIP()} 的回复：无法访问目标主机。";
                                this.pictureBox1.Image = imageList1.Images["Red"];
                            }
                            else if (reply.Status == IPStatus.TimedOut)
                            {
                                info = "请求超时。";
                                this.pictureBox1.Image = imageList1.Images["Red"];
                            }
                            ShowInfo(info);
                        }
                    }
                    catch (Exception e)
                    {
                        ShowInfo(e.Message);
                        this.pictureBox1.Image = imageList1.Images["Red"];
                    }

                    if (cnt == 4)
                    {
                        ShowInfo($"Ping {ip} 结束。");
                        return;
                    }
                }
            });
        }

        private void btnPing_Click(object sender, EventArgs e)
        {
            this.pictureBox1.Image = imageList1.Images["Grey"];
            string ip = ipAddressBox1.Text;
            if (chkDomain.Checked)
            {
                ip = txtDomain.Text.Trim();
            }
            ShowInfo($"正在 Ping {ip} 具有 32 字节的数据：");
            PingAsync(ip, 0);
        }

        private void chkDomain_CheckedChanged(object sender, EventArgs e)
        {
            txtDomain.Enabled = chkDomain.Checked;
            ipAddressBox1.Enabled = !chkDomain.Checked;
        }
    }
}