#define BLYNK_TEMPLATE_ID "TMPL6GCGX5lCc"
#define BLYNK_TEMPLATE_NAME "templete"
#define BLYNK_AUTH_TOKEN "So6HYzMme6sYwnDL0NX1_dapaboHg5z-"

#include <BlynkSimpleEsp32.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <Arduino.h>
#include "SevSeg.h"

SevSeg sevseg;

char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

const int RedPin = 13; 
const int YellowPin = 12;
const int GreenPin = 14;

int redTimeDelay = 10;
int yellowTimeDelay = 1;
int greenTimeDelay = 10;
unsigned long timer;

int onOrOff = 1;

BLYNK_CONNECTED() {
  Blynk.syncVirtual(V0);
  Blynk.syncVirtual(V1);
  Blynk.syncVirtual(V2);
  Blynk.syncVirtual(V3);
}

BLYNK_WRITE(V0) {
  onOrOff = param.asInt();
}

BLYNK_WRITE(V1) {
  redTimeDelay = param.asInt();
}

BLYNK_WRITE(V2) {
  yellowTimeDelay = param.asInt();
}

BLYNK_WRITE(V3) {
  greenTimeDelay = param.asInt();
}

void setup() {
  pinMode(RedPin, OUTPUT);
  pinMode(YellowPin, OUTPUT);
  pinMode(GreenPin, OUTPUT);
  Blynk.begin(auth, ssid, pass);
  Blynk.virtualWrite(V1, redTimeDelay);
  Blynk.virtualWrite(V2, yellowTimeDelay);
  Blynk.virtualWrite(V3, greenTimeDelay);
  Blynk.virtualWrite(V0, onOrOff);
  
  byte numDigits = 4; 
  byte digitPins[] = {5, 18, 2, 19}; 
  byte segmentPins[] = {27, 26, 25, 33, 32, 15, 4, 23};
  bool resistorsOnSegments = false; 
  byte hardwareConfig = COMMON_ANODE; 
  bool updateWithDelays = false; 
  bool leadingZeros = false; 
  bool disableDecPoint = true; 
  
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
  updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(90);
}


void loop() {
  Blynk.run();
  if(onOrOff) {
    Blynk.run(); 
   digitalWrite(RedPin, HIGH);
   delayTime(redTimeDelay);
   digitalWrite(RedPin, LOW);
    Blynk.run();
   digitalWrite(YellowPin, HIGH);
    delayTime(yellowTimeDelay);
    digitalWrite(YellowPin, LOW);
   Blynk.run();
    digitalWrite(GreenPin, HIGH);
    delayTime(greenTimeDelay);
    digitalWrite(GreenPin, LOW);
    
  }

}

void delayTime(int time) {
  timer = millis();
  int count = 0;
  int temp = time;
  while(count <= time + 1) {
    sevseg.refreshDisplay();
    if(millis() - timer >= count * 1000) {
      count++;
      sevseg.setNumber(temp, 0);
      temp--;
    }
  }
}