#include "esp_wifi.h"
#include "esp_http_client.h"
#include "esp_event.h"
#include "esp_log.h"
#include "wifi.h"


// WiFi事件处理函数
static void wifi_event_handler(void* arg, esp_event_base_t event_base,
                               int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        ESP_ERROR_CHECK(esp_wifi_scan_start(NULL, false));
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
        uint16_t ap_num = 0;
        ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_num));
        if (ap_num == 0) {
            ESP_LOGE(TAG, "没有扫描到任何AP");
            return;
        }
        // ap_list = malloc(sizeof(wifi_ap_record_t) * ap_num);
        // ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&ap_num, ap_list));

        // 打印扫描到的AP信息 
        // for (int i = 0; i < ap_num; i++) { 
        //     ESP_LOGI(TAGG, "AP %d - SSID: %s, RSSI: %d", i + 1, ap_list[i].ssid, ap_list[i].rssi);
        // }
    }
}

esp_err_t wifi_scan_start(){
    // esp_event_handler_instance_t inst;
    // ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
    //                                                     ESP_EVENT_ANY_ID,
    //                                                     &wifi_event_handler,
    //                                                     NULL,
    //                                                     &inst));
    esp_err_t err = esp_wifi_scan_start(NULL, false);
    if(err == ESP_OK){
        ESP_LOGI("WIFI","开始扫描附近WIFI");
    }
    return err;
}

esp_err_t wifi_scan_list(uint16_t* num,wifi_ap_record_t** list){
    esp_wifi_scan_get_ap_num(num);
    *list = malloc(sizeof(wifi_ap_record_t) * *num);
    esp_err_t err = esp_wifi_scan_get_ap_records(num, *list);
    return err;
}

void wifi_init(){

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    esp_netif_create_default_wifi_sta();

    wifi_init_config_t init_cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&init_cfg));


    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());
}