#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> 
#include <vector>
#include <algorithm>



/**
* 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();

	  
	

	Sequence* seq = isIdExist(argv[1],dataset);
	if(seq){
		//add files from directory
		Image *img = seq->newImage();
		img->next(); 
		struct dirent *dir;
		DIR *d;
		printf("open dir:%s ", argv[2]);
		d = opendir(argv[2]);
		printf("done.\n"); 

		printf("get max interval:");
		int interval=getMaxInterval(dataset,seq->getName())+1;
		printf("%i\n",interval); 

		
		char buff[1000];
		vector<string> files;

		if (d){
			while ((dir = readdir(d)) != NULL){
				printf("check file %s %i\n", dir->d_name,dir->d_type==DT_UNKNOWN );
				//fflush(stdout);
				if ( dir->d_type != DT_DIR){
					printf("add to list %s\n", dir->d_name);
					files.push_back(dir->d_name);
		 	
			//
					/*JSONObject picture;
					picture[L"path"]=new JSONValue(StringToWString(dir->d_name));

					sprintf(buff,"%d.jpg",interval);		
					string new_name=string(buff);	
					string name=string(dir->d_name);
			
					picture[L"new_name"]=new JSONValue(CharToWString(buff));		
					array.push_back(new JSONValue(picture));
	
					img->add(seq->getName(),interval,name);
					img->insert->execute(); 
					interval++;
*/

				}
		  	}
		  	closedir(d);

			sort(files.begin(),files.end());
			for(int i=0;i<files.size();i++){
				string filename=files[i];					
				printf("upload %s\n", filename.c_str());
				string name=string(filename);	
				img->add(seq->getName(),interval,name);
				img->insert->execute(); 
				interval++;	
			}

			
		}
		img->next();
		
	}

	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);*/

	return 0;
}
