#include <Arduino.h>

const char* DEVICE_TYPE = "button";
const char* FW_VERSION  = "1.3.0";

// число каналов устройства (1..8)
extern const uint8_t CHANNEL_NUM = 2;

#include <sh_core.h>
#include "ButtonLogic.h"

// D1 mini пример:
// LED ленты (NeoPixel) на GPIO4 (D2)
const uint8_t SIGNAL_LED = 4; // default 4

static String extract_json_string_value_local(const String &body, const String &key) {
  String pattern = "\"" + key + "\"";
  int keyIndex = body.indexOf(pattern);
  if (keyIndex < 0) return "";

  int colonIndex = body.indexOf(':', keyIndex);
  if (colonIndex < 0) return "";

  int firstQuote = body.indexOf('"', colonIndex + 1);
  if (firstQuote < 0) return "";

  int secondQuote = body.indexOf('"', firstQuote + 1);
  if (secondQuote < 0) return "";

  return body.substring(firstQuote + 1, secondQuote);
}

static int extract_json_int_value_local(const String &body, const String &key) {
  String pattern = "\"" + key + "\"";
  int keyIndex = body.indexOf(pattern);
  if (keyIndex < 0) return -1;

  int colonIndex = body.indexOf(':', keyIndex);
  if (colonIndex < 0) return -1;

  int i = colonIndex + 1;
  while (i < (int)body.length() && body[i] == ' ') i++;

  long v = 0;
  bool any = false;
  while (i < (int)body.length()) {
    char c = body[i];
    if (c < '0' || c > '9') break;
    any = true;
    v = v * 10 + (c - '0');
    i++;
  }
  if (!any) return -1;
  return (int)v;
}

void appendStatusJsonFields(String &json) {
  json += ",\"indicators\":\"";
  if (deviceMode == DEVICE_MODE_SETUP) {
    json += "setup";
  } else if (WiFi.status() != WL_CONNECTED) {
    json += "nowifi";
  } else {
    json += "none";
  }
  json += "\"";

  json += ",\"channels\":[";
  for (uint8_t ch = 0; ch < CHANNEL_NUM; ch++) {
    if (ch) json += ",";
    json += "{\"id\":" + String(ch) + ",\"indicator\":\"";

    IndicatorState st = get_channel_indicator(ch);
    switch (st) {
      case IND_ENABLED:  json += "enabled"; break;
      case IND_DISABLED: json += "disabled"; break;
      case IND_MUTE:     json += "mute"; break;
      case IND_WAITING:  json += "waiting"; break;
      case IND_WARNING:  json += "warning"; break;
      case IND_ERROR:    json += "error"; break;
    }

    json += "\"}";
  }
  json += "]";
}

void appendAboutJsonFields(String &json) {
  json += ",\"channels\":" + String(CHANNEL_NUM);
  json += ",\"has_indicators\":true";
}

bool deviceHandleAction(const String &action,
                        const String &paramsJson,
                        String &errorCode,
                        String &errorMessage)
{
  if (action == "set_channel_state") {
    int ch = extract_json_int_value_local(paramsJson, "channel");
    if (ch < 0 || ch >= (int)CHANNEL_NUM) {
      errorCode = "IllegalActionOrParams";
      errorMessage = "Invalid channel";
      return false;
    }

    String st = extract_json_string_value_local(paramsJson, "state");
    st.toLowerCase();

    if      (st == "enabled")  set_channel_indicator((uint8_t)ch, IND_ENABLED);
    else if (st == "disabled") set_channel_indicator((uint8_t)ch, IND_DISABLED);
    else if (st == "mute")     set_channel_indicator((uint8_t)ch, IND_MUTE);
    else if (st == "warning")  set_channel_indicator((uint8_t)ch, IND_WARNING);
    else if (st == "error")    set_channel_indicator((uint8_t)ch, IND_ERROR);
    else {
      errorCode = "IllegalActionOrParams";
      errorMessage = "Invalid state";
      return false;
    }

    return true;
  }

  errorCode = "IllegalActionOrParams";
  errorMessage = "Unknown action";
  return false;
}

void deviceHandleReset() {
  for (uint8_t ch = 0; ch < CHANNEL_NUM; ch++) {
    set_channel_indicator(ch, IND_DISABLED);
    clear_channel_temp(ch);
  }
}

void setup() {
  coreSetup();
  button_logic_setup();
}

void loop() {
  coreLoop();
  delay(0);
  button_logic_loop();
}
