#include "luma_master.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include <FS.h>
#include <LittleFS.h>
#include "JsonConstrain.h"
#include <esp_now.h>
#include <WiFi.h>
#include "global.h"

static const char* tag = "lumaM";
uint8_t broadcastAddress[] = {0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF};
uint8_t availableStiks = 0;
LUMA_NODE lumaStation[LUMA_NODE_MAX_COUNT];
bool LUMASTIKS_READY = false;

TaskHandle_t LumaMaster_Task_Handle;

bool SendRegistrationPacket = false;
LUMA_PACKET RegistrationPacket;
esp_now_peer_info_t TempNode;



QueueHandle_t lumaQueue = xQueueCreate( 4, sizeof( LUMA_PACKET ) );

void Init_Luma_Master(void){

	if (esp_now_init() != ESP_OK) {
		ESP_LOGD(tag, "Error initializing ESP-NOW\n");
		return;
	}

	xTaskCreatePinnedToCore(LumaMaster_Task, "LumaMaster_Task", 1024*6, NULL, 1, &LumaMaster_Task_Handle, CONFIG_ARDUINO_RUNNING_CORE);
	ESP_LOGV(tag, "Initialized  LumaMaster task created...");

	esp_now_register_recv_cb(Luma_Master_Data_Received);
	esp_now_register_send_cb(Luma_Master_Data_Sent);
}

void LumaMaster_Task(void *parameters){

	while(1){
		vTaskSuspend(NULL);

		if(SendRegistrationPacket){
			Luma_Send_Packet(TempNode.peer_addr, RegistrationPacket);
		}
	}


	LUMA_PACKET lumaPacket;

	while(1){
		xQueueReceive( lumaQueue, &lumaPacket, portMAX_DELAY );

		switch(lumaPacket.type){
			case LPT_RAW:
				break;
			case LPT_REG:
				Luma_Send_Packet(TempNode.peer_addr, lumaPacket);
				break;
			case LPT_ANIM:
				Luma_Master_Broadcast(lumaPacket);
				break;
			default:
				break;
		}
	}
}

void Luma_Master_Data_Sent(const uint8_t *mac_addr, esp_now_send_status_t status){

}

void Luma_Master_Data_Received(const uint8_t *mac, const uint8_t *data, int len){

	LUMA_PACKET *packet = (LUMA_PACKET*)data;

	printf("** Data Received **\n\n");
	printf("Received from MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
	printf("Length: %d byte(s)\n", len);
	printf("Data: %d\n\n", data[0]);
	
	switch(packet->type){
		case LPT_RAW:
			break;
		case LPT_REG:
			LUMA_REGISTER_PACKET *reg = (LUMA_REGISTER_PACKET*)&packet->data;
			ESP_LOGD(tag, "Node SSID: %s", reg->ssid);

			// Register
			memcpy(TempNode.peer_addr, mac, 6);
			TempNode.channel = WiFi.channel();
			Luma_Add_Peer(TempNode);

			// Notify Peer
			RegistrationPacket.type = LPT_REG;
			xQueueSend( lumaQueue, &RegistrationPacket, 100 );
			break;
		//default:
		//	break;
	}
}

void Luma_Master_Broadcast(LUMA_PACKET packet){
	
}


