#include "simpleReflowController.h"

boolean start = false;

unsigned int uiSec;
unsigned long timestamp = 0;
short fuzziness = 5;
unsigned int historyTemp[320];

CRGB leds[NUM_LEDS];

void setup() {
	initPorts();

	Serial.begin(9600);
	Serial.println("Hello World!");

	initTFT();
	initTermocouple();

	FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);

	leds[0] = CRGB::Black;
	FastLED.show();

	start = true;
	uiSec = 0;
	timestamp = millis();

}

void loop() {

	while (!start) {
		//wait for start press and show current temp
		// wait  for cooling down
	}
	//clearTFT();

	if (millis() > (timestamp + 1000)) {
		timestamp = millis();
		secIncrease();
	}

	double currentTemp = getTemp();
	profileStep currentProfile = getProfile(uiSec);

	if (getTemp() < ((currentProfile.temp) - fuzziness)) {

		leds[0] = CRGB::Red;
		FastLED.show();

		digitalWrite(SSR1, LOW);
		digitalWrite(SSR2, LOW);

	}

	if (getTemp() > currentProfile.temp) {

		leds[0] = CRGB::Green;
		FastLED.show();

		digitalWrite(SSR1, HIGH);
		digitalWrite(SSR2, HIGH);
	}

	if ((uiSec % 5) == 0) {
		clearTFT();
		setHeader(currentTemp, uiSec, currentProfile.temp);
		setProfile();
		setGraph(currentProfile.name, uiSec);
		setStatus("active");
	}

}

void initPorts() {
	pinMode(SSR1, OUTPUT);
	pinMode(SSR2, OUTPUT);
	pinMode(PIEZO, OUTPUT);

	digitalWrite(SSR1, HIGH);
	digitalWrite(SSR2, HIGH);
	digitalWrite(PIEZO, HIGH);
}

void secIncrease() {
	historyTemp[uiSec] = getTemp();
	uiSec++;
	Serial.print("sec: ");
	Serial.println(uiSec);
	//double testTemp = getProfileTemp(uiSec).temp;

}

profileStep getProfile(int pSec) {
// from https://www.compuphase.com/electronics/solderprofile-standard-timepoints.png

	profileStep step;
	step.temp = 0.0;
	step.name = "404";
	step.starttime = 0;
	step.endtime = 0;

	if (pSec == -1) {
		step.temp = 50;
		step.name = "start cooling";
		step.starttime = 0;
		step.endtime = 0;
		return step;
	}

	if (pSec <= 90) {
		step.temp = map(pSec, 0, 90, 0.0, 150.0);
		step.name = "preheating";
		step.starttime = 0;
		step.endtime = 90;
		return step;
	}

	if (pSec <= 180) {
		step.temp = 150.0;
		step.name = "soak";
		step.starttime = 91;
		step.endtime = 180;
		return step;
	}

	if (pSec <= 240) {
		step.temp = map(pSec, 180, 240, 150, 240);
		step.name = "reflow";
		step.starttime = 181;
		step.endtime = 240;
		return step;
	}

	if (pSec <= 270) {
		step.temp = 240;
		step.name = "reflow";
		step.starttime = 241;
		step.endtime = 270;
		return step;
	}
	if (pSec > 270) {
		step.temp = map(pSec, 270, 320, 240, 0);
		step.name = "cooling";
		step.starttime = 271;
		step.endtime = 320;
		return step;
	}

	return step;
}

