#include <stdio.h>
#include <stdlib.h>
#include "user_button.h"
#include "iot_button.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/timers.h"


#include "../EPD//include/EPD.h"


static const char *LOG_TAG = "user button";



extern QueueHandle_t button_Data_queue;
extern SemaphoreHandle_t button_semaphore;


static button_handle_t user_button_handle[KEY_NUM] = {0};

static button_handle_t user_powerbutton_handle[3] = {0};
TimerHandle_t btn_timer_handle;
bool is_setting = false;
bool is_reset_net = false;//配网


uint16_t adc_value[][2]=
{
    {BAOYANG_MIN_ADC,BAOYANG_MAX_ADC},
    {FENGCUN_MIN_ADC,FENGCUN_MAX_ADC},
    {GUZHUANG_MIN_ADC,GUZHANG_MAX_ADC},
    {DAILIAO_MIN_ADC,DAILIAO_MAX_ADC},
    {TINGJI_MIN_ADC,TINGJI_MAX_ADC},
    {YUNXING_MIN_ADC,YUNXING_MAX_ADC},
};






uint16_t power_adc_value[][2]=
{
    {0,100},
    {1000,1900},
    {2000,3063},
};


int  find_key_value(int value)
{
    int key = 0xff;

    for(int i  =0 ;i<6;i++)
    {
        if( 
            (adc_value[i][1]>=value)&&
            (adc_value[i][0]<=value)
          )
          {

            key = i;
            printf("key vaule %d\r\n",i);
             
               break;
          }

    }


      return key;

}






static void user_button_single_click_cb(void *arg,void *usr_data);

static void power_long_press_start_cb(void *arg,void *usr_data);
static void power_long_press_hold_cb(void *arg,void *usr_data);
static void power_long_press_up_cb(void *arg,void *usr_data);


static void power_single_press_cb(void *arg,void *usr_data);


static void user_button_single_UP_cb(void *arg,void *usr_data);



static void power_button_multi_press_cb(void *arg,void *usr_data);



static void power_left_single_press_cb(void *arg,void *usr_data)
{
    printf("%s\r\n",__FUNCTION__);
}

static void power_right_single_press_cb(void *arg,void *usr_data)
{
    printf("%s\r\n",__FUNCTION__);
}


int button_idx = 0;



int power_button_idx = 0;

int power_button_mult_time = 0;

void btn_timer_Callback(TimerHandle_t xTimer)
{
    ESP_LOGW(LOG_TAG, "btn_timer_Callback");
    if(is_setting)
    {
        is_setting = false; 
    }
    else if (is_reset_net)
    {
        is_reset_net = false; 
    }
    

    is_setting = 0;
    //xTimerStop(btn_timer_handle,0);
}

void button_init(adc_oneshot_unit_handle_t adc_handle)
{
    int i;
    printf("button_init\n");

    #if 1
	button_config_t adc_btn_cfg = {
	    .type = BUTTON_TYPE_ADC,
	    .long_press_time = CONFIG_BUTTON_LONG_PRESS_TIME_MS,
	    .short_press_time = CONFIG_BUTTON_SHORT_PRESS_TIME_MS,
	    .adc_button_config = {
	        .adc_channel = 7,
            .adc_handle = &adc_handle,
	    },
	};
    //左边6个按键初始化
    for(i = 0;i < KEY_NUM ;i++)
    {
        adc_btn_cfg.adc_button_config.button_index = i;
        adc_btn_cfg.adc_button_config.min = adc_value[i][0] ;
        adc_btn_cfg.adc_button_config.max = adc_value[i][1] ;
        user_button_handle[i] = iot_button_create(&adc_btn_cfg);
        if(NULL == user_button_handle[i]) {
            printf( "Button create failed");
        }
        button_idx = i;
        int ret = iot_button_register_cb( user_button_handle[i], BUTTON_PRESS_DOWN, user_button_single_click_cb,button_idx);
                  //iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_START, power_long_press_cb,button_idx);
        //iot_button_register_cb( user_button_handle[i], BUTTON_PRESS_UP, user_button_single_click_cb,button_idx);
    }

    #endif

}
void button_deinit(void)
{
    printf("button_deinit\n");
    for(int i=0;i<KEY_NUM;i++)
    {
        iot_button_delete(user_button_handle[i]);
    }
    //iot_button_delete(user_powerbutton_handle[0]);
}


void power_button_init(adc_oneshot_unit_handle_t adc_handle)
{
    btn_timer_handle = xTimerCreate(
    "btn_timer_handle",             
    pdMS_TO_TICKS(10*1000),    
    pdFALSE,                
    0,                     
    btn_timer_Callback         
    );

 int i = 0;



#if 0
    //右边3个按键  目前只是用一个按键 POWER
    button_config_t power_btn_cfg = {
	    .type = BUTTON_TYPE_GPIO,
	    .long_press_time = CONFIG_BUTTON_LONG_PRESS_TIME_MS,
	    .short_press_time = CONFIG_BUTTON_SHORT_PRESS_TIME_MS,
	    .adc_button_config = {
	        .adc_channel = 3,
            .adc_handle = &adc_handle,
	    },
	};

    for(int i = 0;i < 1 ;i++)
    {
        power_btn_cfg.adc_button_config.button_index = i;
        power_btn_cfg.adc_button_config.min = power_adc_value[i][0] ;
        power_btn_cfg.adc_button_config.max = power_adc_value[i][1] ;
        user_powerbutton_handle[i] = iot_button_create(&power_btn_cfg);
        if(NULL == user_powerbutton_handle[i]) {
            printf( "Button create failed");
        }
        button_idx = i;
        
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_PRESS_DOWN, power_single_press_cb,button_idx);
        #if 0
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_START, power_long_press_cb,button_idx);
        #else
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_START, power_long_press_start_cb,button_idx);
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_HOLD, power_long_press_hold_cb,button_idx);
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_UP, power_long_press_up_cb,button_idx);
        #endif






        //注册按键多次按键回调
        button_event_config_t btn_cfg;
        btn_cfg.event = BUTTON_MULTIPLE_CLICK;
        // btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_COUNT_OTA;
        // power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        // iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);
        btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_COUNT_RESET;
        power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);

        btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_BLE_OTA_MODE;
        power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);            


        // //注册按键长按按键回调
        // button_event_config_t btn_long_press_cfg;
        // btn_cfg.event = BUTTON_LONG_PRESS_START;
    }
#else



  button_config_t power_btn_cfg = {
            .type = BUTTON_TYPE_GPIO,
            .long_press_time = CONFIG_BUTTON_LONG_PRESS_TIME_MS,
            .short_press_time = CONFIG_BUTTON_SHORT_PRESS_TIME_MS,
            .gpio_button_config = {
                .gpio_num = 4,
                .active_level = 0,
            },
        };






        for(int i = 0;i < 1 ;i++)
    {
       //power_btn_cfg.adc_button_config.button_index = i;
       //power_btn_cfg.adc_button_config.min = power_adc_value[i][0] ;
       //power_btn_cfg.adc_button_config.max = power_adc_value[i][1] ;


        user_powerbutton_handle[i] = iot_button_create(&power_btn_cfg);
        if(NULL == user_powerbutton_handle[i]) {
            printf( "Button create failed");
        }
        button_idx = i;
        
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_PRESS_DOWN, power_single_press_cb,button_idx);
        #if 0
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_START, power_long_press_cb,button_idx);
        #else
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_START, power_long_press_start_cb,button_idx);
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_HOLD, power_long_press_hold_cb,button_idx);
        iot_button_register_cb( user_powerbutton_handle[i], BUTTON_LONG_PRESS_UP, power_long_press_up_cb,button_idx);
        #endif






        //注册按键多次按键回调
        button_event_config_t btn_cfg;
        btn_cfg.event = BUTTON_MULTIPLE_CLICK;
        // btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_COUNT_OTA;
        // power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        // iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);
        btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_COUNT_RESET;
        power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);


        btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_DIS_RIGHT;
        power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);

        btn_cfg.event_data.multiple_clicks.clicks = POWER_KEY_PRSSS_BLE_OTA_MODE;
        power_button_mult_time = btn_cfg.event_data.multiple_clicks.clicks ;
        iot_button_register_event_cb(user_powerbutton_handle[i], btn_cfg, power_button_multi_press_cb, power_button_mult_time);            


        // //注册按键长按按键回调
        // button_event_config_t btn_long_press_cfg;
        // btn_cfg.event = BUTTON_LONG_PRESS_START;
    }





#endif




}





void power_button_deinit(void)
{
     for(int i = 0;i < 3;i++)
     iot_button_delete(user_powerbutton_handle[i]);
}


uint8_t button_info = 0;

#include "SPIFFS.h"
#if 0
static void power_long_press_cb(void *arg,void *usr_data)
{
      switch ((int)usr_data)
      {
        case 0:
        printf("power key long press start\r\n");
        button_info = POWER_ON_INTO_STATUS_CHANGE_VALUE;
            if(xQueueSend(button_Data_queue,&button_info,0) != true)
            {
                ESP_LOGE(LOG_TAG,"queue send is fail");
                return;
            }
        break;
        case 1:
        printf("power left key long press\r\n");
        break;
      }
}
iot_button_get_long_press_hold_cnt((button_handle_t)arg)
#else
static void power_long_press_start_cb(void *arg,void *usr_data)
{
    // printf("power_long_press_start_cb\n");
}
static void power_long_press_hold_cb(void *arg,void *usr_data)
{
    //设置的长按开始时间后开始计算hold_cnt  长按开始时间设置为1s，cnt计算时间间隔（SERIAL_TICKS）也设置为1s
    uint16_t hold_cnt = iot_button_get_long_press_hold_cnt((button_handle_t)arg);
    ESP_LOGE(LOG_TAG," BUTTON_LONG_PRESS_HOLD[%d],count is [%d]\n", iot_button_get_ticks_time((button_handle_t)arg), hold_cnt);

    switch ((int)hold_cnt)
    {
    case 1:
    {
         ESP_LOGE(LOG_TAG,"case 1");
         button_info = POWER_ON_INTO_DIS_RIGHT;
        if(xQueueSend(button_Data_queue,&button_info,0) != true)
            {
                ESP_LOGE(LOG_TAG,"queue send is fail");
                return;
            }
    }
    case 2://设置模式，长按3s进入
        if(is_setting && is_reset_net)
        {
            ESP_LOGE(LOG_TAG,"err:OTA 和 重新配网 同时");
            return;
        }
        if(is_setting)
        {
            button_info = POWER_ON_INTO_OTA_VALUE;
            if(xQueueSend(button_Data_queue,&button_info,0) != true)
            {
                ESP_LOGE(LOG_TAG,"queue send is fail");
                return;
            }
        }

        if(is_reset_net)
        {
            button_info = POWER_ON_INTO_RESET_VALUE;
            if(xQueueSend(button_Data_queue,&button_info,0) != true)
            {
                ESP_LOGE(LOG_TAG,"queue send is fail");
                return;
            }
        }
    break;
    case 4://5s开关机
        button_info = POWER_ON_INTO_STATUS_CHANGE_VALUE;
        if(xQueueSend(button_Data_queue,&button_info,0) != true)
        {
            ESP_LOGE(LOG_TAG,"queue send is fail");
            return;
        }
    break;
    default:
        //printf(" BUTTON_LONG_PRESS_HOLD[%d],count is [%d]\n", iot_button_get_ticks_time((button_handle_t)arg), hold_cnt);
    break;
    }
}
static void power_long_press_up_cb(void *arg,void *usr_data)
{
    // printf("power_long_press_up_cb\n");
}
#endif



#include "esp_sleep.h"

static void power_single_press_cb(void *arg,void *usr_data)
{

      switch ((int)usr_data)
      {
          case 0:
          printf("power sigle press\r\n");

                  if(Machine_info.power_status == 1)  //开机
                {

                        button_info = POWER_ON_PRESS_VALUE;

                        if(xQueueSend(button_Data_queue,&button_info,0) != true)
                    {
                        ESP_LOGE(LOG_TAG,"queue send is fail");
                        return;
                    }

                    
                }else 
                {
                    button_info = POWER_OFF_PRESS_VALUE;  //关机状态下单击按键
                if(xQueueSend(button_Data_queue,&button_info,0) != true)
                    {
                        ESP_LOGE(LOG_TAG,"queue send is fail");
                        return;
                    }
                }
   
          break;




          case 1:
          printf("power left single press\r\n");

          break;

          case 2:
          printf("power right single press\r\n");

          break;
      }
}


static void user_button_single_click_cb(void *arg,void *usr_data)
{
    is_setting = false;
    is_reset_net = false;
    switch ((int)usr_data)
    {
    case BAOYANG_KEY:
            button_info = 6;
            ESP_LOGD(LOG_TAG,"bao yang");
        break;
    case FENGCUN_KEY:
            button_info = 5;
            ESP_LOGD(LOG_TAG,"feng cun");
        break;
    case GUZHUANG_KEY:
            button_info = 4;
            ESP_LOGD(LOG_TAG,"gu zhang");
        break;
    case DAILIAO_KEY:
            button_info = 3;
            ESP_LOGD(LOG_TAG,"dai liao");
        break;
    case TINGJI_KEY:
            button_info = 2;
            ESP_LOGD(LOG_TAG,"ting ji");
        break;
    case YUNXING_KEY:
            button_info = 1;
            ESP_LOGD(LOG_TAG,"yun xing");
        break;
    default:
        break;
    }

#if 0
    if(xSemaphoreTake(button_semaphore, 0) != true)
    {  
        ESP_LOGE(LOG_TAG,"button mutex  is fail,not send lora queue");
        return;
    }

    xSemaphoreGive(button_semaphore);
#endif   

    if(Machine_info.power_status == 0)  //关机
    {
        printf("power off not refresh\r\n");
        return;
    }

        if(left_refresh_timer_isActive() == true)
        {
            return;
        }
    
    if(xQueueSend(button_Data_queue,&button_info,0) != true)
    {
        ESP_LOGE(LOG_TAG,"queue send is fail");
        return;
    }

    
}



static void power_button_multi_press_cb(void *arg,void *usr_data)
{
    if(Machine_info.power_status == 0)  //关机
    {
        printf("关机状态\r\n");
        return;
    }
    switch ((int)usr_data)
    {
        case POWER_KEY_PRSSS_BLE_OTA_MODE:
        if(!is_setting && !is_reset_net) //当前非配置模式
        {
            is_setting = true;
            xTimerStart(btn_timer_handle, 0);
            printf("短按2次\r\n");
        }
        break;
        case POWER_KEY_PRSSS_DIS_RIGHT:
            printf("短按3次\r\n");
            send_button_key_queue((uint8_t)POWER_ON_INTO_DIS_RIGHT);
        break;
        case  POWER_KEY_PRSSS_COUNT_RESET:
            if(!is_setting && !is_reset_net)
            {
                is_reset_net = true;
                xTimerStart(btn_timer_handle, 0);
                printf("短按4次\r\n");
            }
        break;
    }
}






static void user_button_single_UP_cb(void *arg,void *usr_data)
{


    
}

void send_button_key_queue(uint8_t value)
{

         button_info = value;
         if(xQueueSend(button_Data_queue,&button_info,0) != true)
        {
            ESP_LOGE(LOG_TAG,"queue send is fail");
            return;
        }
}







