#include <Arduino.h>
#include <WiFi.h>
#include <WifiMulti.h>
#include <HTTPClient.h>

WiFiMulti wifiMulti;
int imageNum;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  String imageNum;
  for (uint8_t t=4; t>0; t--){
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }
  wifiMulti.addAP("OSU_Access", "");
}
void picSelect(){
//stores potentiameter reading into variable PotVal
  float PotVal= analogRead(34);
  //Converts potentiameter reading to angle  
  float PotAng= PotVal*(270.0 / 4095);

  //Printing out potentiameter angle
  Serial.print("Your potentiameter angle is ");
  Serial.println(PotAng);

  if (PotAng>-1 && PotAng<67.5){
    imageNum=1;
  }
  else if (PotAng>67.5 && PotAng<135){
    imageNum=2;
  }
  else if (PotAng>135 && PotAng<202.5){
    imageNum=3;
  }
  else if (PotAng>202.5 && PotAng<271){
    imageNum=4;
  }
  else{
    Serial.println("Error, try again");
  }
  Serial.print("Your image choice was: ");
  Serial.println(imageNum);
  //separate readings
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
  if((wifiMulti.run()==WL_CONNECTED)){ //wait for WiFi connection
    HTTPClient http; //Creates an HTTPClient object to be used
    //Begins a request we will eventually POST
    http.begin("https://web.engr.oregonstate.edu/~blancolb/engr103/adddata.php");
    //Setup this request to look like an HTML form
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    //Data to send wtih HTTP POST
    picSelect(); //receive value from Pot
    String myString="image=";
    myString=myString + imageNum;
    Serial.print("POST data to send: ");
    Serial.println(myString);
    
    // Send HTTP POST request
    int httpCode=http.POST(myString);
    if (httpCode>0){
      if(httpCode==HTTP_CODE_OK){
        String payload=http.getString();
        Serial.println(payload);
      }
      else{
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);
      }
    }
    http.end(); //End this request.
    Serial.println("");
  }
  delay(5000);
}
