#include "kt.h"
#include "app_task.h"
#include "avctp_user.h"

extern void kt_auto_mute_pa_init(void);

static u16 led_timer_id = 0;
static int led_cnt = 0;

/* static int mute_test = 0;
static u8 mute_test_flag = 0; */

void kt_boot_init(void)
{
    // mute pin
    gpio_set_pull_up(KT_CFG_MUTE_PIN, 0);
    gpio_set_pull_down(KT_CFG_MUTE_PIN, 0);
    gpio_set_direction(KT_CFG_MUTE_PIN, 0);
    gpio_set_output_value(KT_CFG_MUTE_PIN, 0);
    PA_MUTE();
    // b led pin
    gpio_set_pull_up(KT_CFG_B_LED_PIN, 0);
    gpio_set_pull_down(KT_CFG_B_LED_PIN, 0);
    gpio_set_direction(KT_CFG_B_LED_PIN, 0);
    KT_CFG_B_LED_OFF();
    // r led pin
    gpio_set_pull_up(KT_CFG_R_LED_PIN, 0);
    gpio_set_pull_down(KT_CFG_R_LED_PIN, 0);
    gpio_set_direction(KT_CFG_R_LED_PIN, 0);
    KT_CFG_R_LED_OFF();
}

extern void eff_file_switch(u8 *path);
/**
 * @brief 切换EQ
 * @param eq_idx EQ索引，0:NORMAL 1:LP
 */
void kt_eq_switch_to(u8 eq_idx)
{
    if (eq_idx == KT_EQ_IDX_LP)
    {
        // LP EQ
        // strcpy(EFF_CFG_FILE_NAME, EQ_FILE_BT);
        printf("kt_eq_switch_to: LP\n");
        eff_file_switch(EQ_FILE_LP);
    }
    else
    {
        // BT EQ
        // strcpy(EFF_CFG_FILE_NAME, EQ_FILE_BT);
        printf("kt_eq_switch_to: BT\n");
        eff_file_switch(EQ_FILE_BT);
    }
}

static void led_timer_callback(void *priv)
{
    /* mute_test++;
    if (mute_test > 100)
    {
        mute_test = 0;
        if (mute_test_flag)
        {
            PA_MUTE();
            mute_test_flag = 0;
        }
        else
        {
            PA_UNMUTE();
            mute_test_flag = 1;
        }
    } */
    
    if (app_get_curr_task() == APP_BT_TASK)
    {
        KT_CFG_R_LED_OFF();
        if (get_bt_connect_status() >= BT_STATUS_CONNECTING)
        {
            KT_CFG_B_LED_ON();
        }
        else
        {
            led_cnt++;
            if (led_cnt < 4)
            {
                KT_CFG_B_LED_ON();
            }
            else if (led_cnt < 8)
            {
                KT_CFG_B_LED_OFF();
            }
            else
            {
                led_cnt = 0;
            }
        }
    }
    else if (app_get_curr_task() == APP_MUSIC_TASK)
    {
        KT_CFG_R_LED_OFF();
        led_cnt++;
        if (led_cnt < 10)
        {
            KT_CFG_B_LED_ON();
        }
        else if (led_cnt < 20)
        {
            KT_CFG_B_LED_OFF();
        }
        else
        {
            led_cnt = 0;
        }
    }
    else
    {
        KT_CFG_R_LED_ON();
        KT_CFG_B_LED_OFF();
    }
}
static void start_led_timer(void)
{
    if (led_timer_id)
    {
        sys_timer_del(led_timer_id);
        led_timer_id = 0;
    }

    sys_timer_add(NULL, led_timer_callback, 50);
}

void kt_init(void)
{
    printf("kt_init\n");
    kt_auto_mute_pa_init();
    start_led_timer();

    //gpio_set_output_value(KT_CFG_MUTE_PIN, 1);
}