#include "WiFiNet.h"

WiFiNet::WiFiNet(
    int stationMode,
    const char* stationSSID,
    const char* stationPassword,
    const char* apSSID,
    const char* apPassword,
    const char* hostname,
    int connectTimeout){
    config.stationMode = stationMode;
    config.stationSSID = String(stationSSID);
    config.stationPassword = String(stationPassword);
    config.apSSID = String(apSSID);
    config.apPassword = String(apPassword);
    config.hostname = String(hostname);
    config.connectTimeout = connectTimeout;
}

int WiFiNet::connect(){
    config.fromFile("/config.json");
    #ifdef ESP32
    WiFi.setHostname(config.hostname.c_str());
    #elif defined(ESP8266)
    WiFi.hostname(config.hostname.c_str());
    #endif
    Serial.println("Hostname: " + config.hostname);
    if(!connectStation()) {
        createAccessPoint();
    }
    startDNS();
    return 1;
}

int WiFiNet::connectStation(){
    if(config.stationMode == 0) return 0;
    
    int wifiConnectStart = millis();
    WiFi.mode(WIFI_STA);
    WiFi.setAutoReconnect(true);
    WiFi.begin(config.stationSSID.c_str(), config.stationPassword.c_str());
    Serial.println("connect to " + config.stationSSID);
    
    // TODO use tasks
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
        if(millis() - wifiConnectStart >= (uint)config.connectTimeout) {
            Serial.println("wifi connect timeout");
            return 0;
        }
    }
    Serial.println("IP address: " + WiFi.localIP().toString());
    Serial.println(WiFi.localIP().toString());
    return 1;
}

int WiFiNet::createAccessPoint(){
    Serial.println("Starting SoftAP: " + String(config.apSSID));
    WiFi.disconnect();
    WiFi.mode(WIFI_AP);
    WiFi.softAP(config.apSSID.c_str(), config.apPassword.c_str());
    String softApPrt = "SoftAP IP: " + WiFi.softAPIP().toString();
    Serial.println(softApPrt.c_str());
    return 1;
}

// TODO make user configurable services
int WiFiNet::startDNS() {
    if (!MDNS.begin(config.hostname.c_str())) {
         Serial.println("Error setting up MDNS responder!");
         return 0;
    } else {
        Serial.println("mDNS responder started");
        MDNS.addService("http", "tcp", 80);
    }
    return 1;
}