#include "esp_system.h"
#include "esp_log.h"
#include "driver/i2c.h"

#include "H2201_i2c.h"
#include "H2201_V1_IC1.h"
#include "H2201_V1_IC1_PARAM.h"
#include "SigmaStudioFW.h"

void H2201_i2c_master_init(void)
{
    i2c_config_t i2c_config = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = I2C_MASTER_SDA_IO,
        .sda_pullup_en = GPIO_PULLUP_DISABLE,
        .scl_io_num = I2C_MASTER_SCL_IO,
        .scl_pullup_en = GPIO_PULLUP_DISABLE,
        .master.clk_speed = I2C_MASTER_FREQ_HZ,
        // .clk_flags = 0,          /*!< Optional, you can use I2C_SCLK_SRC_FLAG_* flags to choose i2c source clock here. */
    };
    esp_err_t err;
    if ((err = i2c_param_config(I2C_MASTER_NUM, &i2c_config)) != ESP_OK)
    {
        ESP_LOGE(H2201_I2C_TAG, "%s i2c param config failed: %s\n", __func__, esp_err_to_name(err));
        return;
    }
    if ((err = i2c_driver_install(I2C_MASTER_NUM, I2C_MODE_MASTER, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0)) != ESP_OK)
    {
        ESP_LOGE(H2201_I2C_TAG, "%s i2c driver config failed: %s\n", __func__, esp_err_to_name(err));
        return;
    }
}

void H2201_i2c_adau1761_init(void)
{
    default_download_IC1();
}

void H2201_i2c_beep(void)
{
    ADI_REG_TYPE beep_on[4] = {0x00, 0x80, 0x00, 0x00};
    SIGMA_WRITE_REGISTER_BLOCK(DEVICE_ADDR_IC1, MOD_BEEPSWITCH_ISON_ADDR, 4, beep_on);
    vTaskDelay(400 / portTICK_PERIOD_MS);
    ADI_REG_TYPE beep_off[4] = {0x00, 0x00, 0x00, 0x00};
    SIGMA_WRITE_REGISTER_BLOCK(DEVICE_ADDR_IC1, MOD_BEEPSWITCH_ISON_ADDR, 4, beep_off);
}

void H2201_i2c_mastervolume(uint8_t volume)
{    
    printf("Master vol %d\n", volume);
    SIGMA_WRITE_REGISTER(DEVICE_ADDR_IC1, REG_PLAYBACK_HEADPHONE_LEFT_IC1_ADDR, volume);
    vTaskDelay(10 / portTICK_PERIOD_MS);
    SIGMA_WRITE_REGISTER(DEVICE_ADDR_IC1, REG_PLAYBACK_HEADPHONE_RIGHT_IC1_ADDR, volume);
}