#include "ble_text_sensor.h"

#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/core/application.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"

#ifdef USE_ESP32

namespace esphome::ble_client {

static const char *const TAG = "ble_text_sensor";

void BLETextSensor::loop() {
  // Parent BLEClientNode has a loop() method, but this component uses
  // polling via update() and BLE callbacks so loop isn't needed
  this->disable_loop();
}

void BLETextSensor::dump_config() {
  LOG_TEXT_SENSOR("", "BLE Text Sensor", this);
  char service_buf[esp32_ble::UUID_STR_LEN];
  char char_buf[esp32_ble::UUID_STR_LEN];
  char descr_buf[esp32_ble::UUID_STR_LEN];
  ESP_LOGCONFIG(TAG,
                "  MAC address        : %s\n"
                "  Service UUID       : %s\n"
                "  Characteristic UUID: %s\n"
                "  Descriptor UUID    : %s\n"
                "  Notifications      : %s",
                this->parent()->address_str(), this->service_uuid_.to_str(service_buf),
                this->char_uuid_.to_str(char_buf), this->descr_uuid_.to_str(descr_buf), YESNO(this->notify_));
  LOG_UPDATE_INTERVAL(this);
}

void BLETextSensor::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
                                        esp_ble_gattc_cb_param_t *param) {
  switch (event) {
    case ESP_GATTC_OPEN_EVT: {
      if (param->open.status == ESP_GATT_OK) {
        ESP_LOGI(TAG, "[%s] Connected successfully!", this->get_name().c_str());
        break;
      }
      break;
    }
    case ESP_GATTC_CLOSE_EVT: {
      this->status_set_warning();
      this->publish_state("");
      break;
    }
    case ESP_GATTC_SEARCH_CMPL_EVT: {
      this->handle = 0;
      auto *chr = this->parent()->get_characteristic(this->service_uuid_, this->char_uuid_);
      if (chr == nullptr) {
        this->status_set_warning();
        this->publish_state("");
        char service_buf[esp32_ble::UUID_STR_LEN];
        char char_buf[esp32_ble::UUID_STR_LEN];
        ESP_LOGW(TAG, "No sensor characteristic found at service %s char %s", this->service_uuid_.to_str(service_buf),
                 this->char_uuid_.to_str(char_buf));
        break;
      }
      this->handle = chr->handle;
      if (this->descr_uuid_.get_uuid().len > 0) {
        auto *descr = chr->get_descriptor(this->descr_uuid_);
        if (descr == nullptr) {
          this->status_set_warning();
          this->publish_state("");
          char service_buf[esp32_ble::UUID_STR_LEN];
          char char_buf[esp32_ble::UUID_STR_LEN];
          char descr_buf[esp32_ble::UUID_STR_LEN];
          ESP_LOGW(TAG, "No sensor descriptor found at service %s char %s descr %s",
                   this->service_uuid_.to_str(service_buf), this->char_uuid_.to_str(char_buf),
                   this->descr_uuid_.to_str(descr_buf));
          break;
        }
        this->handle = descr->handle;
      }
      if (this->notify_) {
        auto status = esp_ble_gattc_register_for_notify(this->parent()->get_gattc_if(),
                                                        this->parent()->get_remote_bda(), chr->handle);
        if (status) {
          ESP_LOGW(TAG, "esp_ble_gattc_register_for_notify failed, status=%d", status);
        }
      } else {
        this->node_state = espbt::ClientState::ESTABLISHED;
        // For non-notify characteristics, trigger an immediate read after service discovery
        // to avoid peripherals disconnecting due to inactivity
        this->update();
      }
      break;
    }
    case ESP_GATTC_READ_CHAR_EVT: {
      if (param->read.handle == this->handle) {
        if (param->read.status != ESP_GATT_OK) {
          ESP_LOGW(TAG, "Error reading char at handle %d, status=%d", param->read.handle, param->read.status);
          break;
        }
        this->status_clear_warning();
        this->publish_state(reinterpret_cast<const char *>(param->read.value), param->read.value_len);
      }
      break;
    }
    case ESP_GATTC_NOTIFY_EVT: {
      if (param->notify.handle != this->handle)
        break;
      ESP_LOGV(TAG, "[%s] ESP_GATTC_NOTIFY_EVT: handle=0x%x, value=0x%x", this->get_name().c_str(),
               param->notify.handle, param->notify.value[0]);
      this->publish_state(reinterpret_cast<const char *>(param->notify.value), param->notify.value_len);
      break;
    }
    case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
      if (param->reg_for_notify.status == ESP_GATT_OK && param->reg_for_notify.handle == this->handle)
        this->node_state = espbt::ClientState::ESTABLISHED;
      break;
    }
    default:
      break;
  }
}

void BLETextSensor::update() {
  if (this->node_state != espbt::ClientState::ESTABLISHED) {
    ESP_LOGW(TAG, "[%s] Cannot poll, not connected", this->get_name().c_str());
    return;
  }
  if (this->handle == 0) {
    ESP_LOGW(TAG, "[%s] Cannot poll, no service or characteristic found", this->get_name().c_str());
    return;
  }

  auto status = esp_ble_gattc_read_char(this->parent()->get_gattc_if(), this->parent()->get_conn_id(), this->handle,
                                        ESP_GATT_AUTH_REQ_NONE);
  if (status) {
    this->status_set_warning();
    this->publish_state("");
    ESP_LOGW(TAG, "[%s] Error sending read request for sensor, status=%d", this->get_name().c_str(), status);
  }
}

}  // namespace esphome::ble_client
#endif
