

#include <SPI.h>
#include <LiquidCrystal.h>

#include "MqttDefines.h"
#include "MqttUtiles.h"
#include "MqttVarManager.h"

#include "LcdMQTTViewer.h"

void LcdMQTTViewer::envia(char* txt, int pos, int line)
{
	lcd->setCursor(pos, line);
	int l = strlen(txt);
	if (l < nchar)
		for (int i = l; i < nchar; i++)
			txt[i] = ' ';
	txt[nchar] = 0;
	lcd->print(txt);
}
LcdMQTTViewer::LcdMQTTViewer()
{
	maxpan = 0;
	tiempo = 0;
	incre_t = 10 * 1000;
	for (int i = 0; i < MAXINFOLCD; i++)
	{
		LcdConf[i].ivar=-1;
		LcdConf[i].formatLCD[0] = 0;
		LcdConf[i].pan = 255;
	}
}
void LcdMQTTViewer::setTimer(int seg)
{
	incre_t = seg * 1000;
}

void LcdMQTTViewer::envia(int pan)
{
  char val[16];
	char buf[32];
	for (int i = 0; i < maxtInfo; i++)
	{
		if (LcdConf[i].pan != pan)
			continue;
     if(LcdConf[i].ivar>=0)
     {
     MqttVar *v=vars->Get(LcdConf[i].ivar);
     if(v==NULL)
      continue;
   //pilla valor
   if(v->flags & MqttVar::FLOAT_VAR)
      dtostrf(v->val.f,3, 2, val);
   else
      sprintf(val, "%d", (int)v->val.i);
      sprintf(buf, LcdConf[i].formatLCD, val);
    }
     else
     
     strcpy( buf, LcdConf[i].formatLCD);
		
   
		envia(buf,0, LcdConf[i].line);
	}
}

void LcdMQTTViewer::inicia(MqttVarManager *v, LiquidCrystal* lcdEx, int digi, int lines)
{
  vars=v;
	lcd =lcdEx;
	nchar = digi;
	lcd->begin(nchar, lines);
 for(int i=0; i<lines; i++)
 {
    envia("Iniciando",0,i);
 }
}
void LcdMQTTViewer::loop()
{
  if (!MqttUtiles::pasa_incre(&tiempo, incre_t))
    return;
  #ifdef DEBUG_PS
     Serial.println("Refres lcd");
     #endif
  envia(panActual);
  panActual = (panActual + 1) % (maxpan+1);
 
}

void LcdMQTTViewer::add(byte ivar, char* formatLCD, int line, int pan)
{
	if (maxtInfo >= MAXINFOLCD)
		return;
	LcdConf[maxtInfo].ivar=ivar;
	strcpy(LcdConf[maxtInfo].formatLCD, formatLCD);
	LcdConf[maxtInfo].line = line;
	LcdConf[maxtInfo].pan = pan;
	maxtInfo++;
 //recalcula numero de pantallas
	if (maxpan < pan)
		maxpan = pan;
}
