#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <string>
#include <opencv2\opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#pragma warning(disable:4996)
#pragma comment(lib, "WS2_32.lib")
using namespace std;

#define SERVER_ADDRESS "127.0.0.1"
#define PORT 5150

void sendCTPath(const char* path) {
	WSADATA wsaData;
	SOCKET sClient;
	SOCKADDR_IN server;
	//char szMessage[MSGSIZE];
	int ret;
	WSAStartup(0x0202, &wsaData);
	sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	memset(&server, 0, sizeof(SOCKADDR_IN));
	server.sin_family = PF_INET;
	server.sin_port = htons(PORT);
	server.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);
	connect(sClient, (struct sockaddr*)&server, sizeof(SOCKADDR_IN));
	string msg = "CT("+string(path)+")";
	const char* szMessage = msg.c_str();
	send(sClient, szMessage, strlen(szMessage), 0);
	char recvbuf[1024] = { 0 };
	recv(sClient, recvbuf, sizeof(recvbuf), 0);
	printf("%s\n", recvbuf);
	closesocket(sClient);
	WSACleanup();
}

void sendPara(float rx, float ry, float rz, int dx, int dy, float threshold, int flag) {
	WSADATA wsaData;
	SOCKET sClient;
	SOCKADDR_IN server;
	int ret;
	WSAStartup(0x0202, &wsaData);
	sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	memset(&server, 0, sizeof(SOCKADDR_IN));
	server.sin_family = PF_INET;
	server.sin_port = htons(PORT);
	server.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);
	connect(sClient, (struct sockaddr*)&server, sizeof(SOCKADDR_IN));
	string msg = "PARA(" + to_string(rx) + "," + to_string(ry) + "," + to_string(rz) + "," 
		+ to_string(dx) + "," + to_string(dy) + "," + to_string(threshold) + ","+ to_string(flag)+ ")";
	const char* szMessage = msg.c_str();
	send(sClient, szMessage, strlen(szMessage), 0);
	unsigned char* recvbuf = (unsigned char*)malloc(sizeof(unsigned char)*dx*dy);
	recv(sClient, (char*)recvbuf, sizeof(unsigned char)*dx*dy, 0);
	printf("receive drr(%f,%f,%f,%d,%d,%f)\n", rx, ry, rz, dx, dy, threshold);
	closesocket(sClient);
	WSACleanup();
	
	cv::Mat gray1_mat(dx, dy, CV_8UC1, recvbuf);
	cv::imshow("123", gray1_mat);
	cv::waitKey(0);
}

int main() {
	sendCTPath("D:/CT1/CT");
	sendPara(90, 0, 0, 1024, 1024, 0, 1);
	sendPara(90, 25, 0, 512, 512, 0, 1);
	sendPara(90, 0, 77, 1024, 1024, 0, 1);
	sendPara(40, 4, 0, 1024, 1024, 0, 1);
	sendPara(90, 66, 0, 1024, 1024, 0, 1);
	sendPara(30, 0, 60, 1024, 1024, 0, 1);
	sendPara(45, 45, 0, 1024, 1024, 0, 1);
	sendPara(45, 70, 0, 512, 512, 0, 1);
	sendPara(77, 60, 0, 512, 512, 0, 1);
	system("pause");
	return 0;
}