#include <cstdlib>
#include <iostream>

#include "../vtapi/include/vtapi_settings.h"
#include "../vtapi/include/vtapi.h"
#include "JSON.h"
#include "JSONValue.h"
#include <time.h>
#include <dirent.h> 



/**
* Velmi velmi VELMI NEEFEKTIVNI zbytecne se prochazi vsechny sequence
**/
bool isIdAvailable(const char * id,Dataset* dataset){
	Sequence* seq=dataset->newSequence();

	while(seq->next()){		
		if(strcmp(id,seq->getName().c_str())==0){			
			return false;
		}else{
			String path = dataset->getDataLocation() + "datasets/"+id; 
			printf("path:%s\n",path.c_str());
			DIR *d = opendir(path.c_str());			
			if(d != NULL){
				return false;
			}		
		}
	}	
	return true;
}

// Print out function

void print_out(const wchar_t* output) {
	std::wcout << output;
	std::wcout.flush();
}

std::wstring StringToWString(const std::string& s) {
	std::wstring temp(s.length(), L' ');
	std::copy(s.begin(), s.end(), temp.begin());
	return temp;
}

std::wstring CharToWString(const char * s) {
	int len = strlen(s);
	wchar_t* buf = new wchar_t[ len ];
	size_t num_chars = mbstowcs(buf, s, len);
	std::wstring temp(buf, num_chars);
	return temp;
}

unsigned char isFile =0x8;
/**
* param name
* return id sequence
**/
int main(int argc, char** argv)
{
	//if(argc!=2) return -1;

	fpos_t pos;
	fgetpos(stdout, &pos);
	int fd = dup(fileno(stdout));
	freopen ("get_images.log","w",stdout);


	VTApi * vtapi = new VTApi(argc, argv);

	Dataset* dataset = vtapi->newDataset();
	dataset->next();

	srand ( time(NULL) );
   
	char id_str[100];

	Sequence* seq = NULL;
	//nalezeni volneho id
	do{
	int id=rand();
		sprintf(id_str,"%i",id);
	//printf("check id:%s\n",id_str);

	//PROBOHA TOHLE UDELAT JINAK !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!111	
	}while(!isIdAvailable(id_str,dataset));


	seq = dataset->newSequence();
	char path[200];
	sprintf(path,"datasets/%s/",id_str);
	seq->add(id_str, path);
	seq->next();

	
	JSONObject jsRoot;
	JSONObject jsSeq;
	jsSeq[L"name"] = new JSONValue(StringToWString(id_str));	
	jsRoot[L"sequence"]=new JSONValue(jsSeq);  

	   	

	delete (dataset);
	delete (vtapi);

	fflush(stdout);
	//Close file and restore standard output to stdout - which should be the terminal
	dup2(fd, fileno(stdout));
	close(fd);
	clearerr(stdout);
	fsetpos(stdout, &pos);

	JSONValue *value = new JSONValue(jsRoot);
	print_out(value->Stringify().c_str());   
	return 0;
}
