/*
 * productionMode.cpp
 *
 *  Created on: Jan 24, 2018
 *      Author: wn
 */


#include "defines.h"

#define MQTT_MAX_PACKET_SIZE 256

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <PubSubClient.h>

#include "configuration.h"



void callback(char* topic, byte* payload, unsigned int length);




WiFiClientSecure espClient;
PubSubClient client(espClient);

void setup_wifi() {
	delay(10);
	WiFi.mode(WIFI_STA);

	// We start by connecting to a WiFi network
#ifdef DEBUG
	Serial.println();
	Serial.print("Connecting to ");
	Serial.println(configBlock.wifiSsid);
#endif

	WiFi.begin(configBlock.wifiSsid, configBlock.wifiKey);

	while (WiFi.status() != WL_CONNECTED) {
		delay(50);
#ifdef DEBUG
		Serial.print(".");
#endif
	}
	Serial.println("!");

#ifdef DEBUG
	Serial.println("");
	Serial.println("WiFi connected");
	Serial.println("IP address: ");
	Serial.println(WiFi.localIP());
#endif
}




void callback(char* topic, byte* payload, unsigned int length) {
  const uint8_t BUFSIZE = 128;
  if ((length + 1) >= BUFSIZE) {  // 1 for terminating NUL
#ifdef DEBUG
	  Serial.println("Received message too long, ignore it");
#endif
  } else {
    char buffer[BUFSIZE];
    memcpy(buffer, payload, length);
    *(buffer + length) = 0;
#ifdef DEBUG
    Serial.print("Received message: ");
    Serial.print(length);
    Serial.print(" ");
    Serial.print(topic);
    Serial.print(" ");
    Serial.println(buffer);
#endif

    if (! strcmp(topic, configBlock.mqttTopicLed1)) {
    	if (! strcmp(buffer, "red")) {
    		digitalWrite(LED_1_RED, HIGH);
    		digitalWrite(LED_1_GREEN, LOW);
    	}
    	if (! strcmp(buffer, "green")) {
    		digitalWrite(LED_1_RED, LOW);
    		digitalWrite(LED_1_GREEN, HIGH);
    	}
    	if (! strcmp(buffer, "off")) {
    		digitalWrite(LED_1_RED, LOW);
    		digitalWrite(LED_1_GREEN, LOW);
    	}
    }

    if (! strcmp(topic, configBlock.mqttTopicLed2)) {
    	if (! strcmp(buffer, "red")) {
    		digitalWrite(LED_2_RED, HIGH);
    		digitalWrite(LED_2_GREEN, LOW);
    	}
    	if (! strcmp(buffer, "green")) {
    		digitalWrite(LED_2_RED, LOW);
    		digitalWrite(LED_2_GREEN, HIGH);
    	}
    	if (! strcmp(buffer, "off")) {
    		digitalWrite(LED_2_RED, LOW);
    		digitalWrite(LED_2_GREEN, LOW);
    	}
    }

  }
}



void reconnect() {
	// Loop until we're reconnected
	while (!client.connected()) {
#ifdef DEBUG
		Serial.print("Attempting MQTT connection...");
#endif
		// Attempt to connect
		//char clientId[128];
		//snprintf(clientId, 127, "esp%s", WiFi.macAddress().c_str());
		if (client.connect(configBlock.mqttClientId, configBlock.mqttUser, configBlock.mqttPass)) {
#ifdef DEBUG
			Serial.println("connected");
#endif
			client.setCallback(callback);

			// Once connected, publish an announcement...
			client.publish(configBlock.mqttDebugTopic, "hello world");
			client.publish(configBlock.mqttDebugTopic, WiFi.localIP().toString().c_str());

			client.subscribe(configBlock.mqttTopicLed1);
			client.subscribe(configBlock.mqttTopicLed2);
		} else {
#ifdef DEBUG
			Serial.print("failed, rc=");
			Serial.print(client.state());
			Serial.println(" try again in 5 seconds");
#endif
			// Wait 5 seconds before retrying
			delay(5000);
		}
	}
}


bool mqtt_connect() {
	bool reconnected = false;
	if (!client.connected()) {
		reconnect();
		reconnected = true;
	}
	client.loop();
	return reconnected;
}


void setupProduction() {
	pinMode(LED_1_GREEN, OUTPUT);
	pinMode(LED_1_RED, OUTPUT);
	pinMode(LED_2_GREEN, OUTPUT);
	pinMode(LED_2_RED, OUTPUT);

	setup_wifi();
	client.setServer(configBlock.mqttBroker, configBlock.mqttPort);
}


void loopProduction() {
	bool reconnected = mqtt_connect();
	static uint32_t reconnectTime = 0;
	if (reconnected) {
		reconnectTime = millis();
	}



}




