#include <WiFi.h>
#include <TridentTD_LineNotify.h>
#include <PubSubClient.h>
#include <HTTPClient.h>

const char* host = "sirtunz.000webhostapp.com";

byte lastButtonState_LINE = HIGH;
byte lastButtonState_NETPIE = HIGH;
byte lastButtonState_DATABASE = HIGH;

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[100];

unsigned long debounceDuration = 50; // millis
unsigned long lastTimeButtonStateChanged_LINE = 0;
unsigned long lastTimeButtonStateChanged_DATABASE = 0;
unsigned long lastTimeButtonStateChanged_NETPIE = 0;

#define LINE_TOKEN  "DXojxQVgvpeVqmg8CNUZg9mTDqn6TPUWwOdgymF817q"
#define BT_LINE 23
#define BT_DATABASE 22
#define BT_NETPIE 21

const char* mqtt_server = "broker.netpie.io";
const int mqtt_port = 1883;
const char* mqtt_Client = "3e43a953-2fb0-460a-a9b8-eec7a98a4298"; // form Cliend ID
const char* mqtt_username = "PvwBSkv4G73Vz3hr3j2msT7hNW3KLgHa"; // form Token
const char* mqtt_password = "YE0hz1FEgRIfr~QuKgjboxrEQTn-W8fJ"; // form Secret

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection…");
    if (client.connect(mqtt_Client, mqtt_username, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("@msg/#");  //subscribe "msg" all messages
    }
    else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println("try again in 5 seconds");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String message;
  String tpc;
  for (int i = 0; i < length; i++) {
    message = message + (char)payload[i];
  }
}


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  pinMode(BT_LINE, INPUT_PULLUP);
  pinMode(BT_NETPIE, INPUT_PULLUP);
  pinMode(BT_DATABASE, INPUT_PULLUP);

  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  LINE.setToken(LINE_TOKEN);
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  float t = random(1.,40.)+(random(1.,9.)/3.);
  float h = random(20.,90.)+(random(1.,9.)/3.);
  String message = "t = " + String(t) + ";

  if (millis() - lastTimeButtonStateChanged_LINE > debounceDuration) {
  byte buttonState = digitalRead(BT_LINE);
   if (buttonState != lastButtonState_LINE) {                                                                                                              
      lastTimeButtonStateChanged_LINE = millis();
      lastButtonState_LINE = buttonState;
      if (buttonState == HIGH) {
        LINE.notify(message);
          Serial.println(message);
          Serial.println("Send complete.");
          Serial.println("---------------------------------");
          delay(1000); // this speeds up the simulation
        }

      }
    }
  
  if (millis() - lastTimeButtonStateChanged_NETPIE > debounceDuration) {
  byte buttonState = digitalRead(BT_NETPIE);
   if (buttonState != lastButtonState_NETPIE) {
      lastTimeButtonStateChanged_NETPIE = millis();
      lastButtonState_NETPIE = buttonState;
      if (buttonState == HIGH) {
        if (!client.connected()) {
            reconnect();
      }
    client.loop();
  
    long now = millis();
    if (now - lastMsg > 2000) {
    lastMsg = now;
    float t = random(1.,40.)+(random(1.,9.)/3.);
    float h = random(20.,90.)+(random(1.,9.)/3.);
    String data = "{\"data\":{\"Temperature\": " + String(t) + "}}";
    Serial.println(data);
    data.toCharArray(msg , (data.length() + 1));
    client.publish("@shadow/data/update", msg);
    client.loop();
    }
    delay(1);
        }
      }
    }

    if (millis() - lastTimeButtonStateChanged_DATABASE > debounceDuration) {
    byte buttonState = digitalRead(BT_DATABASE);
    if (buttonState != lastButtonState_DATABASE) {
      lastTimeButtonStateChanged_DATABASE = millis();
      lastButtonState_DATABASE = buttonState;
      if (buttonState == HIGH) {
        WiFiClient client2;
        const int httpPort = 80;

  if (!client2.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  String url = "/get_data.php?temp=" + String(t) + "";      //ชุด Directory ที่เก็บไฟล์ และตัวแปรที่ต้องการจะฝาก

  Serial.print("Requesting URL: ");
  Serial.println(url);

  client2.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client2.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client2.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client2.available()){
    String line = client2.readStringUntil('\r');
    Serial.print(line);
  }
        }
      }
    }
}