using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;

namespace TimedShutdown
{
    public class PingWidget
    {
        IPAddress _ipAddress = IPAddress.None;
        public bool IsCancellationRequested { get; set; } = false;

        BackgroundWorker contPingBackgroundWorker = new BackgroundWorker();

        public void InitatePingRequest(IPAddress ipAddress)
        {
            _ipAddress = ipAddress;

            contPingBackgroundWorker.DoWork += ContPingBackgroundWorkerDoWork;
            contPingBackgroundWorker.RunWorkerAsync();
        }

        /// <summary>
        /// Will continuously ping the input IP address every 5 seconds,
        /// will stop if a cancellation request is made.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContPingBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {

            while (IsCancellationRequested == false)
            {
                Thread.Sleep(5000);

                Ping pingSender = new Ping();
                IPAddress address = _ipAddress;
                PingReply reply = pingSender.Send(address);

                if (reply.Status == IPStatus.Success)
                    Debug.WriteLine("Ping Success!");
                else
                {
                    Debug.WriteLine(reply.Status);
                } 
            }
        }
    }
}
