#include <TimeLib.h>
#include "arduino_secrets.h"
#include <Servo.h>
#include <WiFi101.h>

const char ssid[] = SECRET_SSID;
const char pass[] = SECRET_PASS;
WiFiClient wifiClient; // Used for the TCP socket connection

Servo blind;

int position = 0;
int photoDiode = A0;
int pdValue = 0;

void setup()
{
    blind.attach(9);
    Serial.begin(9600);
}

void openBlind()
{
    for (position = 0; position <= 180; position += 1)
    {
        blind.write(position);
        delay(15);
    }
    Serial.print("Open Blind End Position: ");
    Serial.print(position);
    Serial.print("\n");
}

void closeBlind()
{
    for (position = 180; position >= 0; position -= 1)
    {
        blind.write(position);
        delay(15);
    }
    Serial.print("Close Blind End Position: ");
    Serial.print(position);
    Serial.print("\n");
}

void loop()
{
    if (WiFi.status() != WL_CONNECTED)
    {
        connectWiFi();
    }
    pdValue = analogRead(photoDiode);
    Serial.println(String(pdValue / 1024.0 * 100) + "%");
    delay(500);
    
    Serial.println("Now from TimeLib module: " + String(hour()) + ":" + String(minute()) + " " + String(day()) + "/" + String(month()) + "/" + String(year()));
    Serial.println("Now from the WiFi module: " + String(getTime()));
    if(getTime() > 0){
        setTime(getTime());
    }
    // if pdValue below 50% and inSchedule then open blind else close blind
    if (pdValue / 1024.0 < 0.5)
    {
        openBlind();
    }
    else
    {
        closeBlind();
    }
    delay(2000);
}

unsigned long getTime()
{
    // get the current time from the WiFi module
    return WiFi.getTime();
}

void connectWiFi()
{
    Serial.print("Attempting to connect to SSID: ");
    Serial.print(ssid);
    Serial.print(" ");

    while (WiFi.begin(ssid, pass) != WL_CONNECTED)
    {
        // failed, retry
        Serial.print(".");
        delay(5000);
    }
    Serial.println();

    Serial.println("You're connected to the network");
    getTime();
    //setTime(getTime());
    Serial.println();
}