#include <FFat.h>
#include "wifi.h"

#include <WiFiClientSecure.h>

#include <Wire.h>
#include "RTClib.h"

#include "files.h"

#include "certs.h"
RTC_DS1307 rtc;
#include "sensor.h"


DateTime now;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("No time available (yet)");
    return;
  }
  Serial.println(&timeinfo, "Time: %Y-%m-%d %H:%M:%S");
}

char jwt[943];

uint32_t iat, jwtexp;
//DateTime laikas;

char laikas[] = "YYYY-MM-DD hh:mm:ss";

void setup() {

  Serial.begin(115200);
  //printf("Flash size: %d bytes\n", spi_flash_get_chip_size());
  
  WiFiClientSecure *cln = new WiFiClientSecure;
  wifiset();
  
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    //Serial.flush();
    //abort();
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  time_t rt = rtc.now().unixtime();
  timeval tv = { rt, 0 };
  settimeofday(&tv, 0);

  printLocalTime();
   //Full Timestamp
  
  if (!FFat.begin(true,"/ft",10,"fat")) {
    Serial.println("FFat Mount Failed");
    return;
  } else Serial.println("FFat mounted.");
  //writeFile(FFat, "/data.txt", "1234567890OK\r\n");

  File f = FFat.open("/data.txt", FILE_APPEND);
  
  now = rtc.now();

  f.println(now.unixtime());
  //laikas = 
  const char*  server = "identitytoolkit.googleapis.com";
  
  //cln->setCACert(root_ca);
  //cln->setCACert(root_ca2);
  cln->setInsecure();
  
  String reqt = "{  \"email\": \"[email protected]\", \"password\":\"123456789\",\"returnSecureToken\":true}";
  String urlt = "/v1/accounts:signInWithPassword?key=AIzaSyDozinTFHn9REYox0W2kiJc1cOQRpcxaRo";
  //identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyDozinTFHn9REYox0W2kiJc1cOQRpcxaRo
  Serial.print("Getting token from password.. " + String(server));
  
  if (!cln->connect(server, 443)) {
    Serial.print(" .. FAILED!\n");
    //char err_buf[256];
    //cln->getLastSSLError(err_buf, sizeof(err_buf));
    //Serial.println(err_buf);
  } else { Serial.print(" ..connected .. ");  
  
    String req = "POST "+urlt+ " HTTP/1.1\r\n"
      "Host: " + String(server) + "\r\n"
      "User-Agent: ESP \r\n"
      "Accept: application/json\r\n"
      "Content-Type: application/json\r\n"
      "Content-Length: " + String(reqt.length()) + "\r\n"
      "\r\n" + reqt + "\r\n";
  
    cln->print(req);
  
    while (cln->connected()) {
      String line = cln->readStringUntil('\n');
      if (line == "\r") {
        //Serial.println("headers received");
        break;
      }
    }
    // if there are incoming bytes available
    // from the server, read them and print them:
    while (cln->available()) {
      String c = cln->readStringUntil('\n');
      if (c.indexOf("idToken")>0) {
        Serial.printf(" token received, length %i.\n", c.length()-12);
        //Serial.println(c);
        
        strncpy(jwt, c.substring(12,c.length()-2).c_str(), sizeof(jwt)-1);
        //Serial.println(c.substring(14,949).c_str());
        //Serial.println(String((c.substring(14,949)).length()));
      } //else {Serial.println("idToken NOT found"); }
      //Serial.print(c);
    }

    cln->stop();
    now = rtc.now();
    
    Serial.println("Token " + String(jwt).substring(610,620) + " will expire at " + now.toString(laikas));
    
    //f.println(laikas.unixtime());
    f.println(jwt);
    
  }
  f.close();
  
  listDir(FFat, "/", 0);
  File ff = FFat.open("/data.txt",FILE_READ);
  
  //Serial.printf("jwt size: %i\n", sizeof(jwt));
  String line = ff.readStringUntil('\n');
  //if (line.indexOf('OK')>0) Serial.println("OK found");
  Serial.println("time: " + line);
  ff.seek(14);
  ff.read((uint8_t *)jwt,sizeof(jwt)-1);
  
  Serial.printf("jwt: %s\n", jwt);
  
  
  ff.close();
  
  setupDS18B20();

}

void loop() {
  delay(2000);
  yield();
  for (int i = 0; i<1; i++) Serial.printf("\nTemp #%i %f\n",i,getTemperature(tAddr[i]));
}
GND5VSDASCLSQWRTCDS1307+