#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"

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

    const char *target_ip = argv[1];
    int target_port = atoi(argv[2]);
    const char *filename = 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;
    }

    // 打开JPEG文件
    FILE *file = fopen(filename, "rb");
    if (!file) {
        printf("打开文件失败");
        close(sockfd);
        return 1;
    }

    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    rewind(file);

    printf("即将发送JPEG文件: %s, 大小: %ld 字节\n", filename, file_size);

    uint8_t *data = malloc(file_size + sizeof(packHead_s));
    if (!data) {
        printf("内存分配失败\n");
        fclose(file);
        close(sockfd);
        return 1;
    }
    memset(data, 0, file_size + sizeof(packHead_s));

    // 加载JPEG文件数据到内存
    fread(data + sizeof(packHead_s), 1, file_size, file);
    rewind(file);

    // 填充数据包
    fill_pack_for_jpg(data, file_size + sizeof(packHead_s), data + sizeof(packHead_s), file_size, GRAPH_JPG);

    ssize_t total_sent = send_buffer(sockfd, &dest_addr, data, file_size + sizeof(packHead_s));
    if (total_sent > 0)
        printf("发送完成，共发送%ld字节\n", total_sent);
    else
        printf("发送失败\n");

    free(data);
    fclose(file);
    close(sockfd);

    return 0;
}
