// 秒寻科技
// 系统入口
// 系统内存遵从谁申请谁负责释放的原则
// zt
// 2023-02-27

#include "src/includes/includes.h"
#include "src/sysdefine/sysmacro.h"

// 导出所需的全局变量
extern PUB_LOCATION_DATA_T gg_astLocationDataList[PUB_SYS_CARRIER_NUM]; // 定位数据队列

// 系统入口函数
int main()
{
    // 初始化业务模块
    main_module_init();

    // 初始化IMU模块
    imu_init();

    // 测试业务逻辑
    if (PUB_DEBUG_ENABLE)
    {
        main_read_wav();
        // main_read_bin();
    }

    printf("wasm init ok\n");

    return 0;
}

// 初始化各模块
void main_module_init()
{
    // 业务模块初始化
    sysmain_init();

    return;
}

// 从wav文件中读取数据，驱动信号处理模块
void main_read_wav()
{
    // const char *pFileName = "E:\\work\\ips8000\\aplm8000sdk\\wave\\zcq(20251203-09).wav";
    //  const char *pFileName = "E:\\work\\ips8000\\aplm8000sdk\\wave\\rec5-0-5(0245)-btsx.wav";
    const char *pFileName = "E:\\work\\ips8000\\aplm8000sdk\\wave\\zhoutao_6bts_rect_0327.wav";
    int16 *pwData = NULL; // 音频数据存储地址
    uint8 byIsOver = 0;
    uint16 wCounter = 0;
    // char *pFilePaht = "E:\\work\\ips8000\\aplm8000sdk\\output\\lctdata\\audioSourceFile.bin";

    pwData = (int16 *)dmdl_main_get_audio_sample_data();

// 读取wave文件
#pragma pack(push, 1) // 确保结构体按照字节对齐
    typedef struct
    {
        char chunkID[4];
        int chunkSize;
        char format[4];
        char subchunk1ID[4];
        int subchunk1Size;
        short audioFormat;
        short numChannels;
        int sampleRate;
        int byteRate;
        short blockAlign;
        short bitsPerSample;
        char subchunk2ID[4];
        int subchunk2Size;
    } WaveHeader;
#pragma pack(pop) // 恢复默认的对齐方式

    FILE *file = fopen(pFileName, "rb");
    if (file == NULL)
    {
        perror("Error opening file");
        return;
    }

    WaveHeader header;
    if (fread(&header, sizeof(WaveHeader), 1, file) != 1)
    {
        perror("Error reading header");
        fclose(file);
        return;
    }

    int bytesPerSample = header.bitsPerSample / 8;
    int totalSamples = header.subchunk2Size / bytesPerSample;

    int samplesToRead = 12000;
    int bytesRead = 0;

    while (bytesRead < totalSamples)
    {
        int remainingSamples = totalSamples - bytesRead;
        int samplesToReadNow = (remainingSamples >= samplesToRead) ? samplesToRead : remainingSamples;

        memset(pwData, 0, sizeof(int16) * PUB_SLOT_FRAME_LEN);
        int actualRead = (int)fread(pwData, bytesPerSample, samplesToReadNow, file);

        if (actualRead != samplesToReadNow)
        {
            if (feof(file))
            {
                printf("total %d frame\n", wCounter);
                byIsOver = 1;
                break;
            }
            else
            {
                byIsOver = 1;
                perror("Error reading samples");
                fclose(file);
                return;
            }
        }

        // wCounter++;
        // if (wCounter >= 136 && wCounter <= 180)
        // {
        //     util_write_flt32_to_bin_file(pFilePaht, PUB_SLOT_FRAME_LEN, pfData);
        //     dmdl_main(gg_astLocationDataList);
        // }

        // 读文件结束或者数据长度不够一帧
        if (!byIsOver || actualRead != PUB_SLOT_FRAME_LEN)
        {
            // 信号处理
            sysmain_audio_signal_process();
        }

        bytesRead += actualRead;
    }

    return;
}

void main_read_bin()
{
    uint8 byFlag = 1;
    char *pFilePaht = "E:\\work\\ips8000\\aplm8000sdk\\wave\\IPS8000.bin";
    int16 *pwData = NULL; // 音频数据存储地址
    uint16 wReadTimes = 0;

    pwData = (int16 *)dmdl_main_get_audio_sample_data();

    while (byFlag)
    {
        memset(pwData, 0, sizeof(int16) * PUB_SLOT_FRAME_LEN);
        byFlag = util_file_read_int16_from_bin_file(pFilePaht, wReadTimes, PUB_SLOT_FRAME_LEN, pwData);
        if (!byFlag)
        {
            printf("is over\n");
            break;
        }

        sysmain_audio_signal_process();

        wReadTimes++;
    }
}

// 测试矩阵求逆
void main_test_matrix()
{
    flt32 afM1[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    flt32 afM2[16] = {0};
    uint8 bySize = 4;

    matrix_inversion(afM1, afM2, bySize);

    matrix_print(afM1, 4, 4);

    matrix_print(afM2, 4, 4);
}

// 测试fft变换
void main_test_fft()
{
    flt32 afRealDataList[8] = {-0.0000001, -0.0000002, -0.0000003, -0.0000004, 0.0000001, 0.0000002, 0.0000003, 0.0000004};
    flt32 afImagDataList[8] = {0};
    uint16 awButterFlyList[8] = {0};

    // 生成蝴蝶因子
    util_fft_init_butterfly_table(8, (short *)awButterFlyList);

    util_fft_fft(8, afRealDataList, afImagDataList, (short *)awButterFlyList);

    util_fft_ifft(8, afRealDataList, afImagDataList, (short *)awButterFlyList);
}