/**
 * BasicHTTPClient.ino
 *
 *  Created on: 24.05.2015
 *
 */

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#define USE_SERIAL Serial

WiFiMulti wifiMulti;

const int greenLed = 33;
const int redLed = 27;
const int blueLed = 32;

void turnOffPins() {
  digitalWrite(greenLed, LOW);
  digitalWrite(redLed, LOW);
  digitalWrite(blueLed, LOW);
}

void setup() {

    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);
    }

    // Setup WiFi
    wifiMulti.addAP("OSU_Access", "");

    // Setup Pins
    pinMode(greenLed, OUTPUT);
    pinMode(redLed, OUTPUT);
    pinMode(blueLed, OUTPUT);

    turnOffPins();
    digitalWrite(blueLed, HIGH);
}

void loop() {
    // wait for WiFi connection
    if((wifiMulti.run() == WL_CONNECTED)) {

        HTTPClient http;

        // Define the connection
        USE_SERIAL.print("[HTTP] begin...\n");
        http.begin("https://web.engr.oregonstate.edu/~wrighesc/engr103/final_out.php"); //HTTP

        // Start the connection 
        USE_SERIAL.print("[HTTP] GET...\n");
        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);

            // Prepare to change pin color
            turnOffPins();

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                // Get the payload
                String payload = http.getString();
                USE_SERIAL.println(payload);
                if (payload == "true") {
                    // True, green 
                    digitalWrite(greenLed, HIGH);
                } else {
                    // Anything else, red
                    digitalWrite(redLed, HIGH);
                }
            } else {
              // Error, blue
              digitalWrite(blueLed, HIGH);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(1500);
}
