//---------------------------------------------------------------------------
#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;

FILE *f;
const int pocet = 15+numberOfSensors+2;
float dataFile[pocet];
int kroku = 0;

void NactiData(FILE * f, const int pocet, float * data){
        for(int i=0;i<pocet;i++){
                fscanf(f,"%f",&data[i]);
        }
        //getc(f);
        //getc(f);
}

#pragma package(smart_init)
#pragma link "CSPIN"
#pragma link "CGAUGES"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
float lastFrame = 0;
int slide = 0;
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
        if(!kreslitStopu->Checked && slide%5==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);
        }
do
{
        Application->ProcessMessages();
        //naplnuje data jako rychlost a pod.
        char test;
        if(!feof(f)){
                lastFrame = dataFile[0];
                NactiData(f,25,dataFile);
        }
        else
        {
                fclose(f);
                Timer1->Enabled = false;
        }
        robotProperties robot;
        float udajeRobota[pocet];
        robot.id = dataFile[1];
        robot.positionX = dataFile[2];
        robot.positionY = dataFile[3];
        robot.rotation = dataFile[4];
        robot.Rcolor = 192-dataFile[5];
        robot.Gcolor = 192-dataFile[6];
        robot.Bcolor = 255;
        robot.drawingPolomer = 1;
        Memo1->Lines->Add(FloatToStr(dataFile[0]) + " " +
                FloatToStr(dataFile[1]) + " " +
                FloatToStr(dataFile[2]) + " " +
                FloatToStr(dataFile[3]) + " " +
                FloatToStr(dataFile[4]) + " " +
                FloatToStr(dataFile[5]) + " " +
                FloatToStr(dataFile[6]) + " " +
                FloatToStr(dataFile[7]) + " " +
                FloatToStr(dataFile[8]) + " " +
                FloatToStr(dataFile[9]) + " " +
                FloatToStr(dataFile[10]) + " " +
                FloatToStr(dataFile[11]) + " " +
                FloatToStr(dataFile[12]) + " " +
                FloatToStr(dataFile[13]) + " " +
                FloatToStr(dataFile[14])
        );
        //nactiDoRobota(robot,udajeRobota);
        drawSingleRobot(robot,Image1->Canvas);
}while(lastFrame+1 != dataFile[0]);
        slide++;
}

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(prvek != "" || !konec){
		        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;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)
{
        if(OpenDialog1->Execute())
        {
                Edit1->Text = OpenDialog1->FileName;
        }        
}
//---------------------------------------------------------------------------


void __fastcall TForm1::Button3Click(TObject *Sender)
{
        f = fopen(OpenDialog1->FileName.c_str(),"r");
        Timer1->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button4Click(TObject *Sender)
{
        Timer1->Enabled = ! Timer1->Enabled;
        if(Button4->Caption == "pause")
        {
                Button4->Caption = "resume";
        }
        else
        {
                Button4->Caption = "pause";
        }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button5Click(TObject *Sender)
{
        Timer1->Interval /= 2;        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button6Click(TObject *Sender)
{
        Timer1->Interval *= 2;        
}
//---------------------------------------------------------------------------



