
#include "DomoEspManager.h"
DomoEspManager::DomoEspManager()
{
  vars.config(NULL, NULL);
  //vars.AddListenner(&sens);
  //vars.AddListenner(&des);
  sens.Config(&vars);
  sens.buzz=&buzz;
  suscrito=false;
}

void DomoEspManager::inicia(WakeOnLan *pwol, LiquidCrystal *lcd, PubSubClient *mqttClient, WiFiClient* espClient, DomoConfig* conf)
{
  mqttclient=mqttClient;
  #ifdef DEBUG_PS
     Serial.println("Inicia Wifi");
     #endif
  wifi.inicia(espClient, conf->ssidWifi, conf->keyWifi, conf->ideEsp);
  #ifdef DEBUG_PS
     Serial.println("Inicia Mqtt");
     #endif
  mqtt.inicia(mqttClient,conf->ideEsp, conf->hostMQTT, conf->portMQTT, this);
#ifdef DEBUG_PS
     Serial.println("Configura Sensores");
     #endif
  //pasar funcion de configuracion de añadir sensores
  
  
 conf->ConfigGen(&sens, &vars, &lcdm, &wol, &des);
  
 
  #ifdef DEBUG_PS
     Serial.println("Inicia variables");
     #endif
  vars.inicia(mqttClient);
  
    #ifdef DEBUG_PS
     Serial.println("Inicia Sensores");
     #endif
  sens.inicia();
   #ifdef DEBUG_PS
     Serial.println("Iniciado Desencadenadores");
     #endif
 des.inicia(&vars);
 

 
   #if CON_LCD
   #ifdef DEBUG_PS
     Serial.println("Iniciado LCD");
     #endif
    //busca buzzer
  int ibuzzer=-1;
  for(int i=0; i<sens.sens.n; i++)
  {
     #ifdef DEBUG_PS
     Serial.println("busca BUzz");
     #endif
    MqttSensor* s= sens.Get(i);
    #ifdef DEBUG_PS
     Serial.println("busca BUzz 2");
     #endif
    if(s->tipo == MqttSensor::SENS_BUZZ_OUT)
    {
      ibuzzer=s->ivar;
       #ifdef DEBUG_PS
     Serial.println("encuentrado buz");
     #endif
      break;
    }
  }
   #ifdef DEBUG_PS
     Serial.println("inicia LCD");
     #endif
  lcdm.inicia(&vars, lcd, conf->lcd.colum, conf->lcd.lines, ibuzzer);
   #ifdef DEBUG_PS
     Serial.println("iniciado LCD");
     #endif
  #endif
  wol.inicia(pwol);
  
}

void DomoEspManager::loop()
{

  if(!wifi.loop())
    {
      suscrito=false;
      return;
    }

  if(!mqtt.loop())
  {
     suscrito=false;
    return;
  }
    
  if(!suscrito)
  {
    vars.Suscribe();
    #if CON_LCD
    lcdm.suscribe(mqttclient);
    #endif
    wol.suscribe(mqttclient);
    suscrito=true;
  }
  
  sens.loop();
  vars.loop();
  des.loop();
   #if CON_LCD
  lcdm.loop();
  #endif
}

void DomoEspManager::OnMqtt(char* topic, char* payload)
{
   vars.OnMqtt(topic, payload);
   des.OnMqtt(topic, payload);
   #if CON_LCD
   lcdm.OnMqtt(topic, payload);
   #endif

   #if CON_WOL
   wol.OnMqtt(topic, payload);
   #endif
   
   #ifdef DEBUG_PS
    Serial.println("OnMqtt fin");
   #endif
}

void DomoEspManager::SubscribeMqtt(PubSubClient *client_mqtt)
{
  
}
