#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <math.h>
#include "common.h"

#define MAX_TEXT_LOG_LEN    512

int32_t prepare_curve_data(char* inBuff, int32_t inBuffLen, int32_t windowID, int32_t curveNum, int32_t curveType, ...)
{
    va_list args;       // 定义参数列表指针
    int32_t i;

    // 初始化参数列表，curveType是最后一个确定的参数
    va_start(args, curveType);

    printf("inBuffLen: %d\n", inBuffLen);
    printf("windowID: %d\n", windowID);
    printf("curveNum: %d\n", curveNum);
    printf("curveType: %d\n", curveType);

    // 遍历所有float参数（注意使用double类型接收）
    for (i = 0; i < curveNum; i++) {
        // float类型在可变参数中会自动转换为double
        double val = va_arg(args, double);
        printf("var%i: %.2f ", i, val);
    }
    printf("\n");

    // 清理参数列表
    va_end(args);
}

int32_t main(int32_t argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "用法: %s <目标IP> <目标端口> <测试窗口ID>\n", argv[0]);
        return 1;
    }

    const char *target_ip = argv[1];
    int32_t target_port = atoi(argv[2]);
    int8_t windowID = atoi(argv[3]);
    int32_t ret = 0;

    // 初始化网络
    struct sockaddr_in dest_addr;
    int32_t sockfd = init_udp_network(target_ip, target_port, &dest_addr);
    if (sockfd < 0) {
        printf("网络初始化失败\n");
        return 1;
    }

    uint32_t packBufferLen = MAX_TEXT_LOG_LEN + sizeof(packHead_s);
    uint8_t *packBuffer = malloc(packBufferLen);
    if (!packBuffer) {
        printf("内存分配失败\n");
        close(sockfd);
        return 1;
    }

#define TEST_FLOAT_TYPE

#ifdef TEST_FLOAT_TYPE
    float cnt1 = 0.0f;
    float cnt2 = 0.0f;
#elif defined(TEST_INT32_TYPE)
    int32_t cnt1 = 0;
    int32_t cnt2 = 0;
#endif

    while(1)
    {
        memset(packBuffer, 0, packBufferLen);

#ifdef TEST_FLOAT_TYPE
        int32_t realDataBuffLen = fill_pack_for_curve(packBuffer, packBufferLen, CURVE_FLOAT, windowID, 2, sin(cnt1), cos(cnt2));
        ssize_t total_sent = send_buffer(sockfd, &dest_addr, packBuffer, realDataBuffLen);
        if (total_sent > 0)
            printf("窗口%d 发送完成，共发送%ld字节 数据：%.2f, %.2f\n", 0, total_sent, sin(cnt1), cos(cnt2));
        else
            printf("发送失败\n");

        cnt1 += 0.1f;
        cnt2 += 0.1f;
#elif defined(TEST_INT32_TYPE)
        int32_t __cnt1 = cnt1++ % 255;
        int32_t __cnt2 = cnt1++ % 255;
        int32_t realDataBuffLen = fill_pack_for_curve(packBuffer, packBufferLen, CURVE_INT32, windowID, 2, __cnt1, __cnt2);
        ssize_t total_sent = send_buffer(sockfd, &dest_addr, packBuffer, realDataBuffLen);
        if (total_sent > 0)
            printf("窗口%d 发送完成，共发送%ld字节 数据：%d, %d\n", 0, total_sent, __cnt1, __cnt2);
        else
            printf("发送失败\n");
#endif

        usleep(50000);
    }

    free(packBuffer);
    close(sockfd);

    return 0;
}
