#include "WifiAPI.h"
#include "WifiManager.h"

#include "WebsocketServer.h"

void WifiAPI::sendWifiState(websockets::WebsocketsClient &client)
{
  StaticJsonDocument<128> data;
  data["state"] = wifiManager_.stateStr();
  data["hostname"] = wifiManager_.hostname();
  sendToClient<192>(client, MessageCode::WIFI_STATE_RESPONSE, data);
}

void WifiAPI::onClientConnect(websockets::WebsocketsClient &client)
{
  sendWifiState(client);
}

bool WifiAPI::handleMessage(websockets::WebsocketsClient &client, MessageCode code, const char *payload, size_t size)
{
  if (code == MessageCode::WIFI_STATE_GET)
  {
    sendWifiState(client);
    return true;
  }
  else if (code == MessageCode::WIFI_STATE_SET)
  {
    StaticJsonDocument<1024> json;

    DeserializationError err = deserializeMsgPack(json, payload, size);
    if (err)
    {
      sendErrorToClient(client, "Deserialization Error");
      return true;
    }
    if (json.containsKey("reset_to_provisioning") && json["reset_to_provisioning"].as<bool>())
    {
      LOG_INFO("wifi: reset_to_provisioning");
      wifiManager_.resetToApProvisioning();
      restartScheduled_ = true;
      return true;
    }
    else if (json.containsKey("ap_password"))
    {
      LOG_INFO("wifi: ap_password");
      wifiManager_.setApCredentials(json["ap_password"].as<const char *>());
      restartScheduled_ = true;
      return true;
    }
    else if (json.containsKey("sta_ssid") && json.containsKey("sta_password"))
    {
      LOG_INFO("wifi: sta_ssid");
      wifiManager_.setStaCredentials(json["sta_ssid"].as<const char *>(), //
                                     json["sta_password"].as<const char *>());
      restartScheduled_ = true;
      return true;
    }
  }
  else if (code == MessageCode::WIFI_TRIGGER_SCAN)
  {
    WiFi.scanNetworks(true);
    return true;
  }
  return false;
}
