//---------------------------------------------------------------------------
#include <windows.h>
#include <iostream>
#include <string>
#include <vcl.h>
#include <stdio.h>
#include <stdlib.h>
#include "drawSimulation.h"
#include "Unit1.h"
#pragma hdrstop

#define BUFSIZE 4096

WORD wVersionRequested = MAKEWORD(1,1);
WSADATA data;
SOCKET mySocket;
sockaddr_in serverSock;
hostent * gConnectionHost;

SOCKET startViewerListening(char * serverAddress, int connectionPort)
{
	if (WSAStartup(wVersionRequested, &data) != 0)
	{
		std::cerr << "Nepodařilo se inicializovat sokety" << std::endl;
		return INVALID_SOCKET;
	}
	if ((gConnectionHost = gethostbyname(serverAddress)) == NULL)
	{
		std::cerr << "patná adresa" << std::endl;
		WSACleanup();
		return INVALID_SOCKET;
	}
	if ((mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
	{
		std::cerr << "Nelze vytvořit soket" << std::endl;
		WSACleanup();
		return INVALID_SOCKET;
	}
	serverSock.sin_family = AF_INET;
	serverSock.sin_port = htons(connectionPort);
	memcpy(&(serverSock.sin_addr), gConnectionHost->h_addr, gConnectionHost->h_length);
	if (connect(mySocket, (sockaddr *)&serverSock, sizeof(serverSock)) == -1)
	{
		std::cerr << "Nelze navázat spojení" << std::endl;
		WSACleanup();
		return INVALID_SOCKET;
	}
	return mySocket;
}

std::string receiveText(SOCKET mySocket)
{
	int size = -1;
	char buf[BUFSIZE];
	std::string text = "";
	//while ((size != 0) && (size != -1))
	//{
	size = recv(mySocket, buf, BUFSIZE, 0);
	if (size == -1)
	{
		std::cerr << "Nelze přijmout data" << std::endl;
		return "error";
	}
	text.append(buf, buf + size);
	//}
	return text;
}

//globalni zobrazovana data
int motorLeft = 0;
int motorRight =0;
int D = 500;          //velikost zobrazeneho robota
float X = 0;
float Y = 0;
float vl = 0;
float vr = 0;
int const pomer = 10;   //pomer zobrazeni ku pocitani
float uhel = 0; //natoceni robota

bool konec = false;


void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
        Application->ProcessMessages();
}

#pragma package(smart_init)
#pragma link "CSPIN"
#pragma link "CGAUGES"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
        Image1->Canvas->MoveTo(400,400);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
        const int numberOfValues = 32;

        SOCKET mySocket = startViewerListening(EditServer->Text.c_str(), CSviewerPort->Value);
	if(mySocket == INVALID_SOCKET)
	{
		std::cerr << "Invalid socket...";
	}
	bool pokracuj = true;
        std::string prijataData;
        std::string prvek;

        FILE *f;
        f=fopen("data.txt","w");
	while(pokracuj)
	{
		prijataData += receiveText(mySocket);
		if(prijataData == "error")
		{
			pokracuj = false;
                        break;
		}
                int slide = 0;
                while(true){
		        prvek = getLineFromStream(prijataData,'$');
                        fprintf(f,"%s\n",prijataData.c_str());
                        if(prvek == "" || konec)
                                break;
                        float actual[numberOfValues];
                        convertReceiveData(actual, prvek);
                        robotProperties robot;
                        nactiDoRobota(robot,actual);
                        if(!kreslitStopu->Checked && slide%100==0)
                        {
                                Image1->Canvas->Brush->Color = RGB(255,255,255);
                                Image1->Canvas->Pen->Color = RGB(0,0,0);
                                Image1->Canvas->Rectangle(0,0,Image1->Picture->Width,Image1->Picture->Height);
                        }
                        slide++;
                        drawSingleRobot(robot,Image1->Canvas);
                        Application->ProcessMessages();
                }
        }
        fclose(f);
}
//---------------------------------------------------------------------------


void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
        konec = true;
}
//---------------------------------------------------------------------------

