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

namespace MySQLDemo
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // Clear status 
            lblStatus.Text = "";
            lblStatus.Refresh();
            Thread.Sleep(50);

            // Login to the server 
            string conString = string.Format(@"server={0};userid={1};password={2};port={3}", txtIP.Text, txtUsername.Text, txtPassword.Text, txtPort.Text);
            var con = new MySqlConnection(conString);
            try
            {
                lblStatus.Text = "Connecting to MySQL server...";
                lblStatus.Visible = true;
                con.Open();
            }
            catch (Exception ex)
            {
                // Unable to connect to host error
                MessageBox.Show(ex.Message);
                Environment.Exit(1);
            }

            try
            {
                // Update status
                lblStatus.Text = lblStatus.Text + "\nRetrieving data...";

                // Select the cgate database
                MySqlCommand useDatabase = new MySqlCommand("USE cgate", con);
                useDatabase.ExecuteNonQuery();

                // Retrieve the data
                MySqlDataAdapter sqlDA = new MySqlDataAdapter("SELECT name, label, status, value, unit, rawdata, class, date, tz FROM register_acquisition", con);
               
                // Display results
                DataTable dataTbl = new DataTable();
                sqlDA.Fill(dataTbl);
                dgvTable.DataSource = dataTbl;
                lblStatus.Text = lblStatus.Text + string.Format("\nRetrieved {0} nodes", dataTbl.Rows.Count);
            }
            catch (Exception ex)
            {
                // Database/Table/Column does not exist error
                MessageBox.Show(ex.Message);
                Environment.Exit(1);
            }
            
            con.Close();
        }
    }
}
