#include<Arduino.h>
#include<WiFi.h>
#include <WifiMulti.h>
#include<HTTPClient.h>


WiFiMulti wifiMulti;

float maxDistance = 200.0;
float halfDistance = maxDistance/2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println();

  for(uint8_t t = 4; t >0; t--){
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }
  //blue
  pinMode(25,OUTPUT);
  //red
  pinMode(33,OUTPUT);
  //green
  pinMode(32,OUTPUT);

  wifiMulti.addAP("OSU_Access","");
  

}

void loop() {
  // put your main code here, to run repeatedly:
  //need to write code to read data off of engineering webspace
  if((wifiMulti.run()== WL_CONNECTED)){
    
    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    http.begin("https://web.engr.oregonstate.edu/~bartoloc/sonardata.csv");

    Serial.print("[HTTP] GET...\n");
    int httpCode = http.GET();
    
    if(httpCode > 0){
      Serial.printf("[HTTP] GET...code: %d\n",httpCode);
      
      if(httpCode == HTTP_CODE_OK){
        String payload = http.getString();
        float sonarDistance = payload.toFloat();
      //if the object is greater then the max distance output blue
      if(sonarDistance > maxDistance){
        //blue LED on
        digitalWrite(25,HIGH);
      }
      //else if object is between half the distance and the max distance output green
      else if(sonarDistance >= halfDistance && sonarDistance < maxDistance){
        //green LED on
        digitalWrite(32,HIGH);
      }
      //else if object is less then half the distance output red 
      else if(sonarDistance < halfDistance && sonarDistance >= 0){
        //red LED on
        digitalWrite(33,HIGH);
      }
      //else output nothing
      else{
        //turns off all LED
        digitalWrite(25,LOW);
        digitalWrite(32,LOW);
        digitalWrite(33,LOW);
        Serial.println("Error invalid number");
      }
      delay(100);
      //turns off all LED
      digitalWrite(25,LOW);
      digitalWrite(32,LOW);
      digitalWrite(33,LOW);
        
      }
      else{
        Serial.printf("[HTTP]GET...code:%d\n",httpCode);
      }
    }  
    http.end();
  }
  delay(50);
}
