#ifndef __MQTT_H_
#define __MQTT_H_
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <Preferences.h>
#include <WiFiManager.h>
#include <WiFiClient.h>
#include <ArduinoOTA.h>
#include <MQTT.h>
#include <WebServer.h>
#include <glblData.h>
#include <ArduinoJson.h>


#define NTP_SERVER "pool.ntp.org"
#define TZ_INFO "WEST-1DWEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00" // Western European Time

const char HTTP_HEAD_JSON[]         PROGMEM = "text/json";


class MQTT: public PubSubClient{
public:
    bool wifiConnected = false;
    static bool saveConfigFlag;    
    MQTT(void);
    void reconnect(void);
    PubSubClient psclient;
    WiFiClient client;
    Preferences prefs;
    WiFiManager wm;
    void sendStatus(void);
    char* getMqttServer(void);
    uint16_t getMqttPort(void);
    char* getHostname(void);
    char* getMqttTopic(void);
    char* getMyIP(void);
    void begin();
    void loop(void);
    void publish(const char* msg);
    void publish(const char* msg, unsigned int len);
    void publish(const char* msg, bool retained);
    void publish(const char* msg, unsigned int len, bool retained);
    void publish_sub(const char* subtopic, const char* msg);
   
private:
    static void serveData(void);
    static void serveSetValve(void);
    char myIP[16] = "0.0.0.0";
    static constexpr char wifiInitialApPassword[] = "12345678";
    char mqtt_server[40] = "nas.local";
    int mqtt_port = 1883;
    int numValves = 1;
    int defTime_min = 60;
    char hostname[40] = "Gartenwasser_vorn";
    char mqtt_topic[40] = "Gartenwasser/vorn";
    void saveConfigToFlash(void);
    static void saveConfigCallback(void);
    unsigned long lastReconnectTry{0};
    unsigned long lastStatusUpdate{0};
    static WebServer* server;
};
#endif
