#include <iostream>
#include <thread>
#include "Base/export.h"
#include "Bit.h"
#include "Socket/Socket.h"
using Func_Type = void(*)(char* buf, std::uint16_t* len);


int main(int argc, char* argv[]) {
    bool use_dll = false;
    std::string ip = "127.0.0.1";
    uint16_t port = 12345;
    // 检查命令行参数数量
    if (argc >= 2) {
        // 解析 use_dll 参数
        if (std::string(argv[1]) == "true") {
            use_dll = true;
        } else if (std::string(argv[1]) == "false") {
            use_dll = false;
        }

        // 解析 ip 参数（如果有）
        if (argc >= 3) {
            ip = argv[2];
        }

        // 解析 port 参数（如果有）
        if (argc >= 4) {
            try {
                port = std::stoi(argv[3]);
            } catch (const std::invalid_argument& e) {
                std::cerr << "Invalid port number." << std::endl;
                return 1;
            } catch (const std::out_of_range& e) {
                std::cerr << "Port number out of range." << std::endl;
                return 1;
            }
        }
    }



    // 输出解析后的参数
    std::cout << "use_dll: " << (use_dll ? "true" : "false") << std::endl;
    std::cout << "ip: " << ip << std::endl;
    std::cout << "port: " << port << std::endl;

    Func_Type read_func_ptr = nullptr;
    if (use_dll) {
        auto path = Psc::get_abs_path("@/x86_linux_Release_lib9002so/lib9002.so");
        auto lib = Psc::load_library(path);
        if (lib == nullptr) std::exit(1);
        read_func_ptr = (Func_Type)Psc::load_function(lib, "adsb_read");
        if (read_func_ptr == nullptr) std::exit(2);
    }

    Base_Logger_Manager::instance().init();



    Psc::socket::Server_Socket socket;
    socket.type = Psc::socket::Socket_Type::TCP;
    socket.create();


    std::thread read_thread([&socket, ip, port]() {
        socket.listen(ip, port);
    });
    read_thread.detach();
    Psc::socket::socket_logger = new BaseLogger(Psc::get_exe_dir() + "/test_memory_lose.log", 1024 * 1024 * 100, 1);
    //auto play_back_logger = new BaseLogger(Psc::get_exe_dir() + "/play_back.log", 1024 * 1024 * 100, 1);

    std::vector<Psc::socket::Accept_Info> clients;
    while (true) {
        std::string data;

        if (use_dll) {
            char buf[std::numeric_limits<std::uint16_t>::max()];
            std::uint16_t len;
            read_func_ptr(buf, &len);
            data = std::string(buf, len);
            socket.flush_clients();
            socket.write_to_all_clients(data);
            //play_back_logger->debug({}, {}, data + " ");

            pure_log(Psc::get_exe_dir() + "/play_back.log", data + " " + "\n");
        } else {

            data = std::string(100, '7');
            socket.flush_clients();
            socket.write_to_all_clients(data);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

int main2(int argc, char* argv[]) {
    bool use_dll = false;
    std::string ip = "127.0.0.1";
    uint16_t port = 12345;
    // 检查命令行参数数量
    if (argc >= 2) {
        // 解析 use_dll 参数
        if (std::string(argv[1]) == "true") {
            use_dll = true;
        } else if (std::string(argv[1]) == "false") {
            use_dll = false;
        }

        // 解析 ip 参数（如果有）
        if (argc >= 3) {
            ip = argv[2];
        }

        // 解析 port 参数（如果有）
        if (argc >= 4) {
            try {
                port = std::stoi(argv[3]);
            } catch (const std::invalid_argument& e) {
                std::cerr << "Invalid port number." << std::endl;
                return 1;
            } catch (const std::out_of_range& e) {
                std::cerr << "Port number out of range." << std::endl;
                return 1;
            }
        }
    }



    // 输出解析后的参数
    std::cout << "use_dll: " << (use_dll ? "true" : "false") << std::endl;
    std::cout << "ip: " << ip << std::endl;
    std::cout << "port: " << port << std::endl;

    Func_Type read_func_ptr = nullptr;
    if (use_dll) {
        auto path = Psc::get_abs_path("@/x86_linux_Release_lib9002so/lib9002.so");
        auto lib = Psc::load_library(path);
        if (lib == nullptr) std::exit(1);
        read_func_ptr = (Func_Type)Psc::load_function(lib, "adsb_read");
        if (read_func_ptr == nullptr) std::exit(2);
    }




    Psc::socket::Client_Socket socket;
    socket.type = Psc::socket::Socket_Type::TCP;
    socket.create();
    Psc::socket::Sockaddr_In addr;
    if (use_dll) {
        addr = Psc::socket::Sockaddr_In{ip, port};
    } else {
        addr = Psc::socket::Sockaddr_In{ip, port};
    }


    std::cout << "connect:" << addr.to_string() << std::endl;
    socket.set_dest_address(addr);
    bool c = socket.connect();
    while (true) {

        std::string data;
        if (use_dll) {
            char buf[std::numeric_limits<std::uint16_t>::max()];
            std::uint16_t len;
            read_func_ptr(buf, &len);
            data = std::string(buf, len);
        } else {
            data = std::string(100, '7');
        }




        // if (data.size() < 500) {
        //     std::cout << "read[" << data.size() << "]:" << memory2hex(data) << std::endl;
        // } else {
        //     std::cout << "read[" << data.size() << "]:" << std::endl;
        // }
        //std::cout << "read[" << data.size() << "]:" << std::endl;

        int send = socket.send(data);
        if (send == -1) {
            if (Psc::socket::is_needed_reconnect(socket.socket_fd)) {
                std::cout << socket.socket_fd << "  重新连接 "  << std::endl;
                socket.connect();
            }

        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}
