#include "wifi_manager.h"
#include "config.h"
#include <WiFi.h>
#include <esp_wifi.h>

static Preferences prefs;

void wifi_manager_init() {
  prefs.begin("dd3cfg", false);
}

bool wifi_load_config(WifiMqttConfig &config) {
  config.valid = prefs.getBool("valid", false);
  config.ssid = prefs.getString("ssid", "");
  config.password = prefs.getString("pass", "");
  config.mqtt_host = prefs.getString("mqhost", "");
  config.mqtt_port = prefs.getUShort("mqport", 1883);
  config.mqtt_user = prefs.getString("mquser", "");
  config.mqtt_pass = prefs.getString("mqpass", "");
  config.ntp_server_1 = prefs.getString("ntp1", "pool.ntp.org");
  config.ntp_server_2 = prefs.getString("ntp2", "time.nist.gov");
  config.web_user = prefs.getString("webuser", WEB_AUTH_DEFAULT_USER);
  config.web_pass = prefs.getString("webpass", WEB_AUTH_DEFAULT_PASS);
  if (!config.valid) {
    return false;
  }
  return config.ssid.length() > 0 && config.mqtt_host.length() > 0;
}

bool wifi_save_config(const WifiMqttConfig &config) {
  prefs.putBool("valid", true);
  prefs.putString("ssid", config.ssid);
  prefs.putString("pass", config.password);
  prefs.putString("mqhost", config.mqtt_host);
  prefs.putUShort("mqport", config.mqtt_port);
  prefs.putString("mquser", config.mqtt_user);
  prefs.putString("mqpass", config.mqtt_pass);
  prefs.putString("ntp1", config.ntp_server_1);
  prefs.putString("ntp2", config.ntp_server_2);
  prefs.putString("webuser", config.web_user);
  prefs.putString("webpass", config.web_pass);
  return true;
}

bool wifi_connect_sta(const WifiMqttConfig &config, uint32_t timeout_ms) {
  WiFi.mode(WIFI_STA);
  WiFi.begin(config.ssid.c_str(), config.password.c_str());
  uint32_t start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < timeout_ms) {
    delay(200);
  }
  bool connected = WiFi.status() == WL_CONNECTED;
  if (connected) {
    esp_wifi_set_ps(WIFI_PS_MIN_MODEM);
  }
  return connected;
}

void wifi_start_ap(const char *ap_ssid, const char *ap_pass) {
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ap_ssid, ap_pass);
}

bool wifi_is_connected() {
  return WiFi.status() == WL_CONNECTED;
}

String wifi_get_ssid() {
  return WiFi.SSID();
}
