#include <WiFi.h>
#include "time.h"

void blinkLED(int pin) {
  pinMode(pin, OUTPUT);
  delay(500);
  digitalWrite(pin,HIGH);
  delay(500);
  digitalWrite(pin,LOW);
  delay(500);
  digitalWrite(pin,HIGH);
  delay(500);
  digitalWrite(pin,LOW);
}

bool connectWiFi() {  // connect to the wifi with the above defined credentials
  if(WiFi.status() == WL_CONNECTED) { return true; }  // return if not connected
  
  Serial.print("[WiFi] Connecting to WiFi...");

  WiFi.begin(wiFiSSID, wiFiPSK);
  while(WiFi.status() != WL_CONNECTED) {
    delay(2000); Serial.printf(".");
    if(WiFi.status() == WL_NO_SSID_AVAIL) {
      Serial.printf("\n[WiFi] Failed to connect to WiFi \"%s\". Reason: WL_NO_SSID_AVAIL\n", wiFiSSID);
      blinkLED(LED_ON_WIFI_ERROR);
      return false;
    } else if(WiFi.status() == WL_CONNECT_FAILED) {
      Serial.printf("\n[WiFi] Failed to connect to WiFi \"%s\". Reason: WL_CONNECT_FAILED\n", wiFiSSID);
      blinkLED(LED_ON_WIFI_ERROR);
      return false;
    }
  }
  Serial.printf("\n[WiFi] Connected to WiFi \"%s\", got IP-Adress ", wiFiSSID);
  Serial.println(WiFi.localIP());

  return true;
}