#include "udp_scan.hpp"
#include <boost/thread/thread.hpp>
#include <boost/lexical_cast.hpp>
#include <zlog.h>
#include "common/common_func.hpp"
#include "common/global.hpp"

extern zlog_category_t *zct;
extern zlog_category_t *zbt;

UdpSys::UdpSys() : mIoSev(), udpSock(mIoSev, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 7303)) { zlog_info(zct, "UdpQt Init"); }

void UdpSys::ClearConnect() { remoteIp.clear(); }

void UdpSys::StartConnectSysUdp() {
    zlog_info(zbt, "start connect QT");
    if (udpSock.is_open()) {
        boost::asio::socket_base::linger option1(true, 0);
        udpSock.set_option(option1);
        boost::asio::socket_base::send_buffer_size option4(125000);
        udpSock.set_option(option4);
        remoteEndPoint = boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 9998);
        remoteEndPoint.address(boost::asio::ip::address::from_string("127.0.0.1"));
        recvUdpData();
        mIoSev.run();
    }
}

void UdpSys::handle_send_to(const boost::system::error_code& ec, size_t trans) {
    if (ec) {
        zlog_error(zct, "send the udp to sys error! ");
    } else {
        zlog_info(zct, "send the udp to sys ok! ");
    }
}

void UdpSys::SendUdpToSingle(std::string pData) {
    boost::mutex::scoped_lock lock(udpMutex);
    int len = pData.length();
    if (len <= 0) return;
    char* mi = new char[len + 3];
    memset(mi, 0, len + 3);
    strcpy(mi, pData.c_str());
    strcat(mi, "\r\n");
    zlog_info(zct, "sys send single : %s ", pData.c_str());
    udpSock.async_send_to(boost::asio::buffer(mi, len + 3), remoteEndPoint, boost::bind(&UdpSys::handle_send_to, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
    delete[] mi;
}

void UdpSys::recvUdpData() { udpSock.async_receive_from(boost::asio::buffer(m_buffer), senderEndPoint, boost::bind(&UdpSys::HandleRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); }

void UdpSys::HandleRead(const boost::system::error_code& pEc, std::size_t pBytesTransferred) {
    std::string ip = senderEndPoint.address().to_string();
    if (pEc) {
        zlog_error(zct, "pEc value:%d, category name:%s, message:%s", pEc.value(), pEc.category().name(), pEc.message().c_str());
    } else if (pBytesTransferred == 0) {
        zlog_info(zct, "rev has rec!");
        if (pBytesTransferred == 0) {
            zlog_error(zct,"[ Read 0 Bytes ][ %s  Quit ! ]", ip.c_str());
        }
    } else {
        std::string read_cmd(m_buffer.data(), pBytesTransferred);
        zlog_info(zct, "%s", read_cmd.c_str());
        if (read_cmd.length() > 0) {
            AnalysisDataSys(read_cmd);
        }
    }
    recvUdpData();
}

void UdpSys::AnalysisDataSys(std::string cmd) {
    zlog_info(zct, "%s", cmd.c_str());
    Json::Reader recvReader;
    Json::Value JsonVal;
    if (recvReader.parse(cmd, JsonVal)) {
        int cmdType = atoi(JsonVal["cmd"].asString().c_str());
        switch (cmdType) {
            case 3: { //配置服务器
                std::string strServerIp = JsonVal["localServerIpAddress"].asString();
                int localServerPort = JsonVal["localServerPort"].asInt();

                std::string strDataWatchAddedBy = "system";
                if (!JsonVal["dataNodeGatewayAddedBy"].isNull()) {
                    strDataWatchAddedBy = JsonVal["dataNodeGatewayAddedBy"].asString();
                    WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", strDataWatchAddedBy);
                }

                zlog_info(zct, "strServerIp : %s ", strServerIp.c_str());
                if (strServerIp.compare(GlobalConfig::ServerIP) != 0 || localServerPort != GlobalConfig::ServerPort) {
                    GlobalConfig::ServerIP = strServerIp;
                    GlobalConfig::ServerPort = localServerPort;

                    WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", GlobalConfig::ServerIP);
                    WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", std::to_string(GlobalConfig::ServerPort));

                    std::string fileserver = ReadStrByOpt(SERVERCONFIG, "FileServer", "FileServerIpAddress");
                    if (0 == fileserver.compare("0.0.0.0") || 0 == fileserver.length()) {
                        WriteStr2Config(SERVERCONFIG, "FileServer", "FileServerIpAddress", GlobalConfig::ServerIP);
                    }

                    JsonVal["status"] = "ACK";
                    Json::FastWriter fw;
                    std::string str = fw.write(JsonVal);
                    zlog_info(zct, "send info : %s ", str.c_str());
                    boost::asio::ip::udp::endpoint remoteEP(boost::asio::ip::address::from_string(senderEndPoint.address().to_string()), MULTICAST_PORT_SEND);
                    udpSock.async_send_to(boost::asio::buffer(str), remoteEP, boost::bind(&UdpSys::handle_send_to, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
                } else {
                    zlog_info(zbt, "server ip and port not change");
                }
            } break;
            case 4: {
                Json::FastWriter fw;
                std::string status = JsonVal["status"].asString();
                if (status.compare("REQ") == 0) {
                    JsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G.c_str();
                    JsonVal["localServerIpAddress"] = GlobalConfig::ServerIP;
                    JsonVal["status"] = "ACK";
                    std::string data = fw.write(JsonVal);
                    boost::asio::ip::udp::endpoint remoteEP(boost::asio::ip::address::from_string(senderEndPoint.address().to_string()), MULTICAST_PORT_SEND);
                    udpSock.async_send_to(boost::asio::buffer(data), remoteEP, boost::bind(&UdpSys::handle_send_to, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
                }
            } break;
            default: break;
        }
    } else {
        zlog_error(zct, "json parse failed");
    }
}

UdpSys::~UdpSys() {
    if (udpSock.is_open()) udpSock.close();
}
