//#include <ESP8266WiFi.h>//este para esp8266
#include <SPI.h>
#include "MqttVarManager.h"
#include "MqttUtiles.h"
#include <cstring>
#include <PubSubClient.h>

MqttTopicAttay::MqttTopicAttay()
{
  n=0;
  nst=0;
}

char* MqttTopicAttay::Get(int i)
{
  return &str[ind[i]];
}

int MqttTopicAttay::Get(char *topic)
{
  for(int i=0; i<n; i++)
  {
    if(!strcmp(topic,Get(i)))
      return i;
  }
  return -1;
}

int MqttTopicAttay::Add(char *topic)
{
  int i=Get(topic);
  if(i>=0)
    return i;
  i=n;
  n=n+1;
  ind[i]=nst;
  
  nst=nst+strlen(topic)+1;
  strcpy(Get(i), topic);
}

//*******************************************************************

MqttVar::MqttVar()
{
  flags=0;
  val.f=0;
  topic=0;
}

//*******************************************************************
MqttVarArray::MqttVarArray()
{
  n=0;
}

MqttVar* MqttVarArray:: Get(int i)
{
  return &(data[i]);
}
  
MqttVar* MqttVarArray::GetVar(int itopic)
{
  for(int i=0; i<n; i++)
  {
    if(data[i].topic==itopic)
      return &(data[i]);
  }
  return NULL;
}

int MqttVarArray::Add(MqttVar* var)
{
  data[n]=*var;
  n++;
  return n-1;
}
//*******************************************************************

MqttVarManager::MqttVarManager()
{
   
   tiempo_var=0;
   incre_tvar=30*1000;
}

void MqttVarManager::config(MqttVarArray *vArray, MqttTopicAttay* t)
{
  vars=vArray;
   topics=t;
}

int MqttVarManager::OnMqtt(char* topic, char* payload)
{
    char buf[32];
    int res=-1;
    sprintf(buf, "%s",topic);
    int nt=strlen(buf);
    int ng=strlen("/get");
    bool isGet=!strcmp("/get", &buf[nt-ng]);
    buf[nt-ng]=0;
    byte f=MqttVar::OUT_VAR;
    if(isGet)
      f=MqttVar::PRIV_VAR;
    if(strcmp("/set", &buf[nt-ng]))
      return res;//no es ni get ni set

    //comprueba variables
    MqttVar* v;
    for(int i=0; i<vars->n; i++)
    {
      v=vars->Get(i);
      if((v->flags & f) && !strcmp(topics->Get(v->topic),buf))
      {
        if(v->flags & MqttVar::FLOAT_VAR)
          {
            float ff=v->val.f;
            v->val.f=atof(payload);
            if(ff!=v->val.f)
              res=i;
          }
        else
        {
          int ii=v->val.i;
          v->val.i=atoi(payload);
           if(ii!=v->val.i)
              res=i;
        }
        break;//suponemos solo una variable con el mismo topic
      }
    }
  
    return res;
}

void MqttVarManager::loop()
{
  if(MqttUtiles::pasa_incre(&tiempo_var, incre_tvar))
  {
    PublicaVars();   
  }
}

void MqttVarManager::PublicaVars()
{
   char buffer_t[32];
   char buffer_p[24];
   byte f=MqttVar::IN_VAR;
   MqttVar* v;
   for(int i=0; i<vars->n; i++)
   {
      v=vars->Get(i);
      if(v->flags & MqttVar::ACCION_VAR)
        continue;//las de accion solo en el onchange
      if(v->flags & f)
      {
        sprintf(buffer_t, "%s/get",topics->Get(v->topic));
        //Publica valor
        if(v->flags & MqttVar::FLOAT_VAR)
          dtostrf(v->val.f,3, 2, buffer_p);
        else
          sprintf(buffer_p, "%d", (int)v->val.i);
        client_qqtt->publish(buffer_t, buffer_p);
      }
   }
}
void MqttVarManager::inicia(PubSubClient* client_mqtt)
{
    client_qqtt=client_mqtt;
   //suscribe a mqtt------------
   char buffer_t[32];
   MqttVar* v;
   for(int i=0; i<vars->n; i++)
   {
      v=vars->Get(i);
      if(v->flags & MqttVar::OUT_VAR)//suscribe al set
      {
        sprintf(buffer_t, "%s/set",topics->Get(v->topic));
        client_qqtt->subscribe(buffer_t);
      }
      if(v->flags & MqttVar::PRIV_VAR)//suscribe al get
      {
        sprintf(buffer_t, "%s/set",topics->Get(v->topic));
        client_qqtt->subscribe(buffer_t);
      }
   }
}
int MqttVarManager::AddVar(byte flags, char*topic)
{
  MqttVar v;
  v.flags=flags;
  v.topic=topics->Add(topic);
  return vars->Add(&v);
}
MqttVar* MqttVarManager::Get(int i)
{
  return vars->Get(i);
}

void MqttVarManager::OnChange(int ivar)
{
 
   MqttVar* v=vars->Get(ivar);
   byte f= MqttVar::ACCION_VAR;
   if(v->flags & f)
   {
     char buffer_t[32];
     char buffer_p[24];
     //if(v->flags & MqttVar::IN_VAR)
     sprintf(buffer_t, "%s/get",topics->Get(v->topic));
     //else
     //sprintf(buffer_t, "%s/put",topics->Get(v->topic));
     //Publica valor
     if(v->flags & MqttVar::FLOAT_VAR)
        dtostrf(v->val.f,3, 2, buffer_p);
     else
        sprintf(buffer_p, "%d", (int)v->val.i);
     client_qqtt->publish(buffer_t, buffer_p);
   }
}
