using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using UIThread;
using System.Threading;
using System.Net;

namespace MQTT_Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MqttClient client;

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new MqttClient(txtBroker.Text);
                client.Connect("clientCsp");

            }
            catch (Exception)
            {

                MessageBox.Show("No Brocker available");
            }
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        }

        private void client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            // handle message received 
            Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
            String str = Encoding.UTF8.GetString(e.Message);
            String rec ="";
            try
            {
                rec = str.Substring(0, 3);
            }
            catch (Exception)
            {
                str = "";
            }
            if ((rec != "str") && (rec != "no "))
            {
                if (rec == "Tem")
                {
                    this.UIThread(delegate
                    {
                        txtTemperature.AppendText(str);
                        str = "";
                        Refresh();
                    });
                }
                else
                {
                    this.UIThread(delegate
                    {
                        //txtReceived.Text += Encoding.UTF8.GetString(e.Message) +"\r\n";
                        txtReceived.AppendText(str);
                        //SendToThingspeak(str);  // THREAD PROBLEM
                        str = "";
                        Refresh();
                    });
                }
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                client.Disconnect();  // MqttMsgPublished event to disconnect the client.
            }
            catch (Exception)
            {
            }
        }

        private void btnSubscribeTx_Click(object sender, EventArgs e)
        {
            //client.Subscribe(new string[] { "mqtt_tx_600194079615" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            //client.Subscribe(new string[] { "mqtt_tx_6001940792e2" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            client.Subscribe(new string[] { txtTopicTx.Text }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }

        private void btnBertlMove_Click(object sender, EventArgs e)
        {
            String message;
            for (int i = 0; i < 5; i++)
            {
                message = "/?arduino=SetDigital&chan=04&state=1";
                client.Publish(txtTopicRx.Text, Encoding.UTF8.GetBytes(message));
                Thread.Sleep(1000);
                message = "/?arduino=SetDigital&chan=04&state=0";
                client.Publish(txtTopicRx.Text, Encoding.UTF8.GetBytes(message));
                Thread.Sleep(1000);
            }
        }

        private void btnLedD1On_Click(object sender, EventArgs e)
        {
            String message = "/?arduino=SetDigital&chan=04&state=1";
            client.Publish(txtTopicRx.Text, Encoding.UTF8.GetBytes(message));
        }

        private void btnLedD1Off_Click(object sender, EventArgs e)
        {
            //String message = " ?M0=SD&chan=01&state=0";
            String message = "/?arduino=SetDigital&chan=04&state=0";
            client.Publish(txtTopicRx.Text, Encoding.UTF8.GetBytes(message));
        }

        bool flagTemp = true;

        private void btnGetTemperature_Click(object sender, EventArgs e)
        {
            if (flagTemp)
            {
                tmGetTemp.Enabled = true;
                flagTemp = false;
            }
            else
            {
                tmGetTemp.Enabled = false;
                flagTemp = true;
            }


        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            String message = txtMessage.Text;
            client.Publish(txtTopicRx.Text, Encoding.UTF8.GetBytes(message));
        }

        private void tmGetTemp_Tick(object sender, EventArgs e)
        {
            String message = " ?M0=GA&chan=09";
            try
            {
    //            client.Publish(txtTopicRx.Text, Encoding.UTF8.GetBytes(message));
            }
            catch (Exception)
            {
            }
        }

        private void btnHttpRequest_Click(object sender, EventArgs e)
        {
            try
            {
                // Full request URI: http://api.thingspeak.com/update?key=K8HEJ5N112EZOMG5&field1=30&field2=90

                const string WRITEKEY = "K8HEJ5N112EZOMG5";
                string strUpdateBase = "http://api.thingspeak.com/update";
                string strUpdateURI = strUpdateBase + "?key=" + WRITEKEY;
                HttpWebRequest ThingsSpeakReq;
                HttpWebResponse ThingsSpeakResp;

                strUpdateURI += "&field1=" + txtTemp.Text;
                strUpdateURI += "&field2=" + txtHum.Text;

                ThingsSpeakReq = (HttpWebRequest)WebRequest.Create(strUpdateURI);

                ThingsSpeakResp = (HttpWebResponse)ThingsSpeakReq.GetResponse();

                if (!(string.Equals(ThingsSpeakResp.StatusDescription, "OK")))
                {
                    Exception exData = new Exception(ThingsSpeakResp.StatusDescription);
                    throw exData;
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                //throw;
            }
        }
        public void SendToThingspeak(string msg)
        {
            try
            {
                const string WRITEKEY = "K8HEJ5N112EZOMG5";
                string strUpdateBase = "http://api.thingspeak.com/update";
                string strUpdateURI = strUpdateBase + "?key=" + WRITEKEY;
                HttpWebRequest ThingsSpeakReq;
                HttpWebResponse ThingsSpeakResp;

                strUpdateURI += "&field1=" + msg;
                strUpdateURI += "&field2=" + txtHum.Text;

                ThingsSpeakReq = (HttpWebRequest)WebRequest.Create(strUpdateURI);

                ThingsSpeakResp = (HttpWebResponse)ThingsSpeakReq.GetResponse();

                if (!(string.Equals(ThingsSpeakResp.StatusDescription, "OK")))
                {
                    Exception exData = new Exception(ThingsSpeakResp.StatusDescription);
                    throw exData;
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                throw;
            }
        }
    }
}
