#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 "common.h"

#define MAX_TEXT_LOG_LEN    512

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

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

    // 初始化网络
    struct sockaddr_in dest_addr;
    int 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;
    }

    while(1)
    {
        printf("\n请输入要发送的文本日志:\n");
        uint8_t *fgetsBuffer = malloc(256);
        fgets(fgetsBuffer, 256, stdin);

        int32_t realDataBuffLen = 0;
        memset(packBuffer, 0, packBufferLen);
        realDataBuffLen = fill_pack_for_text_log(packBuffer, packBufferLen, windowID, "You input: %s", fgetsBuffer);

        ssize_t total_sent = send_buffer(sockfd, &dest_addr, packBuffer, realDataBuffLen);
        if (total_sent > 0)
            printf("窗口%d 发送完成，共发送%ld字节\n", windowID, total_sent);
        else
            printf("发送失败\n");

        usleep(40000);
    }

    free(packBuffer);
    close(sockfd);

    return 0;
}
