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

/**
* Velmi velmi VELMI NEEFEKTIVNI zbytecne se prochazi vsechny sequence
**/
Sequence* isIdExist(const char * id,Dataset* dataset){
	Sequence* seq=dataset->newSequence();
	while(seq->next()){	
		//printf("%s\n",seq->getName().c_str());	
		if(strcmp(id,seq->getName().c_str())==0){
			return seq;
		}
	}	
	return NULL;
}


/**
* Velmi velmi VELMI NEEFEKTIVNI zbytecne se prochazi vsechny sequence
**/
bool isImgIdAvailable(const char * id,Dataset* dataset){
	Sequence* seq=dataset->newSequence();
	while(seq->next()){	
		//printf("%s\n",seq->getName().c_str());	
		if(strcmp(id,seq->getName().c_str())==0){
			return seq;
		}
	}	
	return NULL;
}


int getMaxInterval(Dataset* dataset, String seq_name)
{
  KeyValues * kv = new KeyValues(*dataset);
  kv->select = new Select(*kv, "SELECT MAX(t1) AS index FROM " + dataset->getDataset() + ".intervals WHERE seqname='"+ seq_name + "';");

  kv->next();

  int max = kv->getInt("index");
  return max;
} 

unsigned char isFile =0x8;
/**
* param sequence_id tmp_photo_directory 
* 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 ("upload_photo.log","w",stdout);


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

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

	srand ( time(NULL) );
   
	//char id_str[100];
	JSONObject jsRoot;
	JSONObject jsSeq;

	Sequence* seq = isIdExist(argv[1],dataset);
	if(seq){
		//add files from directory
		Image *img = seq->newImage();
		img->next(); 
		struct dirent *dir;
		DIR *d;
		d = opendir(argv[2]);


		int interval=getMaxInterval(dataset,seq->getName())+1;

		
		jsSeq[L"id"] = new JSONValue(StringToWString(seq->getName()));
		JSONArray array;
		char buff[1000];

		if (d){
			while ((dir = readdir(d)) != NULL){

				if ( dir->d_type == DT_REG){
					printf("upload %s\n", dir->d_name);
		 	
			//
					JSONObject picture;
					picture[L"path"]=new JSONValue(StringToWString(dir->d_name));

					sprintf(buff,"%d.jpg",interval);		
					string new_name=string(buff);		
					picture[L"new_name"]=new JSONValue(CharToWString(buff));		
					array.push_back(new JSONValue(picture));
	
					img->add(seq->getName(),interval,new_name);
					img->insert->execute(); 
					interval++;
				}
		  	}
		  	closedir(d);
			jsSeq[L"imgs"] = new JSONValue(array);
			jsRoot[L"sequence"]=new JSONValue(jsSeq);  
		}else{
			jsRoot[L"error"]=new JSONValue(L"path is invalid");
		}
		img->next();
		
	}else{
		jsRoot[L"error"]=new JSONValue(L"id is not exist");   	
	}

	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;
}
