#include "threadSendTCP.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <qtcpsocket.h>
#include <PLCDevice.h>
#pragma comment(lib, "ws2_32.lib")

extern PLCDevice* m_PLCTCPDevice;

void threadSendTCP::init(SyncQueue<_TCPSendInfo>* p_TCP_Info_queue, std::string ip_, int port_) {
    ip = QString::fromStdString(ip_);
    port = port_;
    qDebug() << "tcp ip:" << ip << "| tcp port:" << port;
    Local_TCP_Info_queue = p_TCP_Info_queue;

#ifdef __TCPServer
    tcpServer = new QTcpServer(this);
	tcpServer->listen(QHostAddress::Any, port);// Equivalent to QHostAddress("127.0.0.1").
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
	connect(mySocket, SIGNAL(connected()), this, SLOT(onClientConnected()));
	connect(mySocket, SIGNAL(disconnected()), this, SLOT(onClientDisconnected()));
#endif

}
void threadSendTCP::start_work()
{
    //start(HighestPriority);
    start();
}

void threadSendTCP::stop()
{
#ifdef __TCPServer
	if (tcpServer->isListening())
		tcpServer->close();
	if(tcpServer) delete tcpServer;
#endif
    isLoop = false;
    // wait();
	mySocket->deleteLater();
	if (mySocket) delete mySocket;
}

#ifndef __TCPServer
bool threadSendTCP::connectTCP() {
    mySocket = new QTcpSocket();
    //mySocket = new QTcpServer();
    // 取消已有的连接
    mySocket->abort();
    // 连接服务器
    mySocket->connectToHost(ip, port);
    if (!mySocket->waitForConnected(100)) {
        qDebug() << "connect failed!";
        return false;
    }
    qDebug() << "connect successfully!";
    return true;
}
#endif

void threadSendTCP::run()
{
#ifndef __TCPServer
    if (!connectTCP())
    {
        qDebug() << "TCP connect error!";
    }
#endif
    while (isLoop) {
        _TCPSendInfo TCPSendInfo;
        Local_TCP_Info_queue->take(TCPSendInfo);
        num++;
#ifdef __TCPServer
		if (ClientStatus == QAbstractSocket::ConnectedState)
		{
			sendData(&TCPSendInfo, num);
		}
#else
		sendData(&TCPSendInfo, num);
#endif
      //mySocket->write("Hello! here is tcp client!\n");
      //mySocket->flush();
    }
}

void threadSendTCP::sendData(_TCPSendInfo* TCPSendInfo, int Num) {
    //std::string fileName = TCPSendInfo->pics_name + ", " + QString::number(Num).toStdString();
	//mySocket->write(fileName.c_str());
	char temp = num % 10;

    mySocket->write((char*)&temp,sizeof(char));
    //mySocket->write("\n");
    mySocket->flush();

    m_PLCTCPDevice->write_short_2_plc(0, 1, (uint16_t*)& temp);
}

#ifdef __TCPServer
void threadSendTCP::onNewConnection()
{
    mySocket = tcpServer->nextPendingConnection(); //创建socket
	qDebug() << "NewConnectionConnected";
	ClientStatus = QAbstractSocket::ConnectedState;
    
}

void threadSendTCP::onClientConnected()
{
    
    qDebug() << "ClientConnected";
}

void threadSendTCP::onClientDisconnected()
{
    ClientStatus = QAbstractSocket::UnconnectedState;
    qDebug() << "ClientDisconnected";
	mySocket->deleteLater();
}
#endif