#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
WiFiMulti wifiMulti;

void setup() {
    //setup pins
    pinMode(25,OUTPUT);
    pinMode(33,OUTPUT);
    //begin serial output 
    USE_SERIAL.begin(115200);
    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }
    //access osu wifi
    wifiMulti.addAP("OSU_Access", "");
}

void loop() {
    // wait for WiFi connection
    if((wifiMulti.run() == WL_CONNECTED)) {

        HTTPClient http;

        //USE_SERIAL.print("[HTTP] begin...\n");
        // get data from url
        http.begin("https://web.engr.oregonstate.edu/~blancolb/engr103/displayData.php"); //HTTP

        //USE_SERIAL.print("[HTTP] GET...\n");
        // start connection and send HTTP header
        // unused 
        int httpCode = http.GET();

        // httpCode will be negative on error
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            //USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                //get data from server
                String payload = http.getString();
                //USE_SERIAL.println(payload);
                
                //picture 1
                if(payload.indexOf("1")!=-1){
                   digitalWrite(25,LOW);
                   digitalWrite(33,LOW);
                   Serial.println("1");
                }
                //picture 2
                else if (payload.indexOf("2")!=-1){
                  digitalWrite(25,HIGH);
                  digitalWrite(33,LOW);
                  Serial.println("2");
                }
                //picture 3
                else if (payload.indexOf("3")!=-1){
                  digitalWrite(25,LOW);
                  digitalWrite(33,HIGH);
                  Serial.println("3");
                }
                //picture 4
                else if (payload.indexOf("4")!=-1){
                  digitalWrite(25,HIGH);
                  digitalWrite(33,HIGH);
                  Serial.println("4");
                }
                //something bad happened do not exicute
                else{
                  USE_SERIAL.printf("Error, could not check");
                }
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }
    //check every 5 seconds
    delay(5000);
}
