#pragma once

#include "Preferences.h"
#include <WiFi.h>

/**
 * Manages connection and provisioning of WiFI
 * 
 *  Starts in state AP_PROVISIONING, where device is an access point without password.
 *  Device should not work normally in this mode, only API is served to set password.
 *  Two options:
 *    - connect to existing WiFi (station mode), via setStaCredentials
 *    - create secured access point, via setApCredentials
 *  
 * When operating in access point mode, the device IP is 192.168.42.1
 * 
 * call iteration()  regularly, it has a wifiWatchdog to reconnect in station mode if connection was lost
 */
class WifiManager
{
public:
  enum State
  {
    INVALID,
    STA,
    AP_PROVISIONING,
    AP_SECURE,
  };
  WifiManager() : state_(INVALID) {}

  void begin(const String &hostname, const String & wifiStaModeName);

  void setStaCredentials(const char *wifiName, const char *password);
  void setApCredentials(const char *password);
  void resetToApProvisioning();

  void iteration();

  bool inProvisioningMode() const { return state_ == INVALID || state_ == AP_PROVISIONING; }

  State state() const { return state_; }
  const char *stateStr() const { return stateToString(state_); }

  const String & hostname() const { return hostname_; }
  static const char *stateToString(State state);

private:
  void startWifi();
  Preferences prefs_;
  State state_;
  String hostname_;
  String wifiStaModeName_;
};
