/*
   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>

#include "esp_err.h"
#include "esp_log.h"
#include "esp_console.h"

#include <nvs_flash.h>

#include <esp_matter.h>
#include <esp_matter_console.h>
#include "electrical_measurement/electrical_measurement.h"

#include <common_macros.h>
#include <log_heap_numbers.h>

#include <app_priv.h>
#include <app_reset.h>

#include <helpers.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include "freertos/semphr.h"

#include <app/server/CommissioningWindowManager.h>
#include <app/server/Server.h>
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#include <platform/ESP32/OpenthreadLauncher.h>
#include <esp_openthread.h>
#include <esp_openthread_border_router.h>
#include <esp_openthread_lock.h>
#endif

#include <lib/support/CHIPMem.h>
#include <platform/CHIPDeviceLayer.h>

// External variables for electrical sensor initialization
extern bool g_electrical_sensor_created;

#ifdef CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE
#include <app/clusters/diagnostic-logs-server/diagnostic-logs-server.h>
#include <diagnostic-logs-provider-delegate-impl.h>
#include <tracing/esp32_diagnostic_trace/DiagnosticTracing.h>
static uint8_t endUserBuffer[CONFIG_END_USER_BUFFER_SIZE]; // Global static buffer used to store diagnostics
static uint8_t retrievalBuffer[CONFIG_RETRIEVAL_BUFFER_SIZE]; // Global static buffer used to retrieve diagnostics

using namespace chip;
using namespace chip::Tracing;
using namespace chip::Tracing::Diagnostics;
using namespace chip::app::Clusters::DiagnosticLogs;
CircularDiagnosticBuffer diagnosticStorage(endUserBuffer, CONFIG_END_USER_BUFFER_SIZE);
auto  &logProvider = LogProvider::GetInstance();
constexpr uint16_t kRootNodeEndpointId = 0;
#endif // CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE

static const char *TAG = "app_main";

uint16_t app_endpoint_id = 0;
// Semaphore is used to block esp_matter::start(), it will be unblock when we have
// valid device type input from user.
SemaphoreHandle_t semaphoreHandle = NULL;

using namespace esp_matter;
using namespace esp_matter::attribute;
using namespace esp_matter::cluster;
using namespace esp_matter::endpoint;
using namespace chip::app::Clusters;

constexpr auto k_timeout_seconds = 300;

static void app_event_cb(const ChipDeviceEvent *event, intptr_t arg)
{
    switch (event->Type) {
    case chip::DeviceLayer::DeviceEventType::kInterfaceIpAddressChanged:
        ESP_LOGI(TAG, "Interface IP Address changed");
        break;

    case chip::DeviceLayer::DeviceEventType::kCommissioningComplete:
        ESP_LOGI(TAG, "Commissioning complete");
        MEMORY_PROFILER_DUMP_HEAP_STAT("commissioning complete");
        break;

    case chip::DeviceLayer::DeviceEventType::kFailSafeTimerExpired:
        ESP_LOGI(TAG, "Commissioning failed, fail safe timer expired");
        break;

    case chip::DeviceLayer::DeviceEventType::kCommissioningSessionStarted:
        ESP_LOGI(TAG, "Commissioning session started");
        break;

    case chip::DeviceLayer::DeviceEventType::kCommissioningSessionStopped:
        ESP_LOGI(TAG, "Commissioning session stopped");
        break;

    case chip::DeviceLayer::DeviceEventType::kCommissioningWindowOpened:
        ESP_LOGI(TAG, "Commissioning window opened");
        MEMORY_PROFILER_DUMP_HEAP_STAT("commissioning window opened");
        break;

    case chip::DeviceLayer::DeviceEventType::kCommissioningWindowClosed:
        ESP_LOGI(TAG, "Commissioning window closed");
        break;

    case chip::DeviceLayer::DeviceEventType::kFabricRemoved: {
        ESP_LOGI(TAG, "Fabric removed successfully");
        if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) {
            chip::CommissioningWindowManager  &commissionMgr = chip::Server::GetInstance().GetCommissioningWindowManager();
            constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds16(k_timeout_seconds);
            if (!commissionMgr.IsCommissioningWindowOpen()) {
                /* After removing last fabric, this example does not remove the Wi-Fi credentials
                 * and still has IP connectivity so, only advertising on DNS-SD.
                 */
                CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds,
                                                                            chip::CommissioningWindowAdvertisement::kDnssdOnly);
                if (err != CHIP_NO_ERROR) {
                    ESP_LOGE(TAG, "Failed to open commissioning window, err:%" CHIP_ERROR_FORMAT, err.Format());
                }
            }
        }
        break;
    }

    case chip::DeviceLayer::DeviceEventType::kFabricWillBeRemoved:
        ESP_LOGI(TAG, "Fabric will be removed");
        break;

    case chip::DeviceLayer::DeviceEventType::kFabricUpdated:
        ESP_LOGI(TAG, "Fabric is updated");
        break;

    case chip::DeviceLayer::DeviceEventType::kFabricCommitted:
        ESP_LOGI(TAG, "Fabric is committed");
        break;

    case chip::DeviceLayer::DeviceEventType::kESPSystemEvent:
        if (event->Platform.ESPSystemEvent.Base == IP_EVENT &&
                event->Platform.ESPSystemEvent.Id == IP_EVENT_STA_GOT_IP) {
#ifdef CONFIG_OPENTHREAD_BORDER_ROUTER
            static bool sThreadBRInitialized = false;
            if (!sThreadBRInitialized) {
                esp_openthread_set_backbone_netif(esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"));
                esp_openthread_lock_acquire(portMAX_DELAY);
                esp_openthread_border_router_init();
                esp_openthread_lock_release();
                sThreadBRInitialized = true;
            }
#endif
        }
        break;

    case chip::DeviceLayer::DeviceEventType::kBLEDeinitialized:
        ESP_LOGI(TAG, "BLE deinitialized and memory reclaimed");
        MEMORY_PROFILER_DUMP_HEAP_STAT("BLE deinitialized");
        break;

    default:
        break;
    }
}

// This callback is invoked when clients interact with the Identify Cluster.
// In the callback implementation, an endpoint can identify itself. (e.g., by flashing an LED or light).
static esp_err_t app_identification_cb(identification::callback_type_t type, uint16_t endpoint_id, uint8_t effect_id,
                                       uint8_t effect_variant, void *priv_data)
{
    ESP_LOGI(TAG, "Identification callback: type: %d, effect: %d", type, effect_id);
    return ESP_OK;
}

// This callback is called for every attribute update. The callback implementation shall
// handle the desired attributes and return an appropriate error code. If the attribute
// is not of your interest, please do not return an error code and strictly return ESP_OK.
static esp_err_t app_attribute_update_cb(attribute::callback_type_t type, uint16_t endpoint_id, uint32_t cluster_id,
                                         uint32_t attribute_id, esp_matter_attr_val_t *val, void *priv_data)
{
    esp_err_t err = ESP_OK;
    // If user want to use driver, can be called from here.
    if (type == PRE_UPDATE) {
        /* Driver update */
        app_driver_handle_t driver_handle = (app_driver_handle_t)priv_data;
        err = app_driver_attribute_update(driver_handle, endpoint_id, cluster_id, attribute_id, val);
    }
    return err;
}

// Handler function for scheduled electrical measurement work
static void ElectricalMeasurementWorkHandler(intptr_t context)
{
    uint16_t endpoint_id = app_endpoint_id;
    esp_err_t err = electrical_measurement_example(endpoint_id);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize electrical measurement clusters: %d", err);
    }
}

#ifdef CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE
void diagnostic_init()
{
    lock::ScopedChipStackLock lock(portMAX_DELAY);
    LogProvider::LogProviderInit providerInit = {
        .endUserBuffer = endUserBuffer,
        .endUserBufferSize = CONFIG_END_USER_BUFFER_SIZE,
        .retrievalBuffer = retrievalBuffer,
        .retrievalBufferSize = CONFIG_RETRIEVAL_BUFFER_SIZE,
    };
    logProvider.Init(providerInit);
}
#endif // CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE

#ifdef CONFIG_SUPPORT_DOOR_LOCK_CLUSTER
void emberAfDoorLockClusterInitCallback(chip::EndpointId endpoint)
{
    ESP_LOGI(TAG, "Door Lock App: Init Callback endpoint=%d", endpoint);
}
#endif // CONFIG_SUPPORT_DOOR_LOCK_CLUSTER

extern "C" void app_main()
{
    esp_err_t err = ESP_OK;

    /* Initialize the ESP NVS layer */
    nvs_flash_init();

    MEMORY_PROFILER_DUMP_HEAP_STAT("Bootup");

    /* Create a Matter node and add the mandatory Root Node device type on endpoint 0 */
    node::config_t node_config;
    // node handle can be used to add/modify other endpoints.
    node_t *node = node::create(&node_config, app_attribute_update_cb, app_identification_cb);
    ABORT_APP_ON_FAILURE(node != nullptr, ESP_LOGE(TAG, "Failed to create Matter node"));

#ifdef CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE
    endpoint_t *root_node_endpoint = endpoint::get(node, kRootNodeEndpointId);
    esp_matter::cluster::diagnostic_logs::config_t diagnostic_logs_config;
    diagnostic_logs_config.delegate = &logProvider;
    diagnostic_logs::create(root_node_endpoint, &diagnostic_logs_config, CLUSTER_FLAG_SERVER);
#endif // CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE
    MEMORY_PROFILER_DUMP_HEAP_STAT("node created");

    uint8_t device_type_index;
    if (esp_matter::nvs_helpers::get_device_type_from_nvs(&device_type_index) != ESP_OK) {
        semaphoreHandle = xSemaphoreCreateBinary();
        ABORT_APP_ON_FAILURE(semaphoreHandle != nullptr, ESP_LOGE(TAG, "Failed to create semaphore"));

        ESP_LOGI(TAG, "\r\n\r\nEnter command: create --device_type to get started");
        example::console::init();

        xSemaphoreTake(semaphoreHandle, portMAX_DELAY);
        vSemaphoreDelete(semaphoreHandle);
        semaphoreHandle = NULL;

        example::console::deinit();
    } else {
        esp_matter::data_model::create(device_type_index);
    }

    /* Initialize app driver, according to the device_type.
    For now it's just for fan_control driver, Waiting for refinement*/
    app_driver_init();

#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
    /* Set OpenThread platform config */
    esp_openthread_platform_config_t config = {
        .radio_config = ESP_OPENTHREAD_DEFAULT_RADIO_CONFIG(),
        .host_config = ESP_OPENTHREAD_DEFAULT_HOST_CONFIG(),
        .port_config = ESP_OPENTHREAD_DEFAULT_PORT_CONFIG(),
    };
    set_openthread_platform_config(&config);
#endif

    /* Matter start */
    err = esp_matter::start(app_event_cb);
    ABORT_APP_ON_FAILURE(err == ESP_OK, ESP_LOGE(TAG, "Failed to start Matter, err:%d", err));
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "Matter start failed: %d", err);
    }

#ifdef CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE
    diagnostic_init();
#endif // CONFIG_ENABLE_ESP_DIAGNOSTICS_TRACE

    MEMORY_PROFILER_DUMP_HEAP_STAT("matter started");
    // Initialize electrical measurement clusters if electrical sensor was created
    if (g_electrical_sensor_created) {
        ESP_LOGI(TAG, "Initializing electrical measurement clusters for endpoint %d", app_endpoint_id);
        chip::DeviceLayer::PlatformMgr().ScheduleWork(ElectricalMeasurementWorkHandler, reinterpret_cast<intptr_t>(nullptr));
    }

#if CONFIG_ENABLE_CHIP_SHELL
    esp_matter::console::diagnostics_register_commands();
    esp_matter::console::wifi_register_commands();
    esp_matter::console::factoryreset_register_commands();
    esp_matter::console::init();
#ifdef CONFIG_OPENTHREAD_CLI
    esp_matter::console::otcli_register_commands();
#endif // CONFIG_OPENTHREAD_BORDER_ROUTER && CONFIG_OPENTHREAD_CLI

#endif

    while (true) {
        MEMORY_PROFILER_DUMP_HEAP_STAT("Idle");
        vTaskDelay(10000 / portTICK_PERIOD_MS);
    }
}
