#ifndef __MQTT_H_
#define __MQTT_H_

#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <WiFiClient.h>
#include <ArduinoOTA.h>
#include <ui/vars.h>
#include <MQTT.h>
#include <ESPAsyncWebServer.h>
#include <settings.h>
#include <ArduinoJson.h>
#include <SPIFFS.h>
#include <ESPmDNS.h>
#include <time.h>


#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;
    static WiFiUDP udp;
    void sendStatus(void);
    char* getMqttServer(void);
    uint16_t getMqttPort(void);
    char* getHostname(void);
    char* getMqttTopic(void);
    char* getMyIP(void);
    static void receiveTopic(char* topic, byte* payload, unsigned int length);
    void begin();
    void loop(void);
    void publish(const char* msg);
    void publish(String 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, bool retained = false);
    static void remoteLog(const char* str,const char* str2);
    static void remoteLog(const char* str);
    static void remoteLog(const char* str, int32_t num);
    static void remoteLogf(const char* format, ...);
    
   
private:
    static const char* months[];
    static void serveData(AsyncWebServerRequest *request);
    //static void serveIndex(AsyncWebServerRequest *request);
    //static void serveCss(AsyncWebServerRequest *request);
    static void serveOverride(AsyncWebServerRequest *request);
    //static void serveSetValve(AsyncWebServerRequest *request);
   // static void handleWebSocket(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len);
   // static void handleWebSocketMessage(void *arg, uint8_t *data, size_t len);
    static String processor(const String& var);
    static String makeStatusJSON(void);
    static String makeTimerJSON(void);
    void sendMQTTstatus(void);
    void saveConfigToFlash(void);
    static void saveConfigCallback(void);
    unsigned long lastReconnectTry{0};
    unsigned long lastStatusUpdate{0};
    unsigned long lastWSupdate{0};
    static AsyncWebServer* server;
    static AsyncWebSocket* ws;
    static constexpr char wifiInitialApPassword[] = "12345678";
};
#endif
