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


namespace FeanorConfig
{
    public partial class Nodestatus : Form
    {        

        public void Start()
        {
            while( UpdateStatusCheckBox.Checked == true)
            {                               
                this.Invoke(new Action(() => { UpdateStatus.PerformClick();})); // update cms-2 node status (by clicking on update button)
                Thread.Sleep(10000); // 10 sec delay
            }            
        }

        public Nodestatus()
        {
            InitializeComponent();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }

        public void UpdateStatus_Click(object sender, EventArgs e) // update node status
        {       
            try
            {     
                using (WebClient client = new WebClient())
                {
                    string dta = client.DownloadString(nodeURL.Text);   // get url for corresponding node                 

                    Nodestatus nodestate = new Nodestatus();
                    
                    webBrowser1.Navigate("about:blank");        
                    if (webBrowser1.Document != null)
                    {
                        webBrowser1.Document.Write(string.Empty);       // empty viewer
                    }
                    webBrowser1.DocumentText = dta;                     // place incoming html in viewer
                }
            }
            catch
            {
                Console.WriteLine("Status request error!");
                System.Windows.Forms.MessageBox.Show("No response from CMS-2 node");
            }
        }

        private void Close_Click(object sender, EventArgs e)
        {           
            this.Close();
        }

        private void nodeURL_TextChanged(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void UpdateStatusCheckBox_CheckedChanged(object sender, EventArgs e)
        {            
            Thread rtd = new Thread(Start); // initialize thread

            if (UpdateStatusCheckBox.Checked == true)
            {
                rtd.Start(); // start thread                
            }
            else if (UpdateStatusCheckBox.Checked == false)
            {
                rtd.Abort();   
                             
            }
        }       
    }
}
