#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

#include "../vtapi/include/vtapi_settings.h"
#include "../vtapi/include/vtapi.h"
#include "JSON.h"
#include "JSONValue.h"


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

int getImageCount(Dataset * dataset, Sequence * seq){
	
  	KeyValues * kv = new KeyValues(*dataset);
  	kv->select = new Select(*kv, "SELECT MAX(t1) AS index FROM " + dataset->getDataset() + ".intervals WHERE seqname='"+ seq->getName() + "';");
  	// obtaining data
  	kv->next();
  	int count = kv->getInt("index");   

	

  return count;
}

/**
 * Remove image
 * remove_image gallery_id img_name	
 * 
 * @param argc
 * @param argv
 * @return sucess
 */
int main(int argc, char** argv) {
	/*fpos_t pos;
	fgetpos(stdout, &pos);
	int fd = dup(fileno(stdout));
	freopen ("get_images.log","w",stdout);
*/

	JSONObject jsRoot;
	JSONObject jsSeq;	

	VTApi * vtapi = new VTApi(argc, argv);
	Dataset* dataset = vtapi->newDataset();
	dataset->next();
	
	String seq_name=String(argv[1]);
	String img_name=String(argv[2]);

	Sequence* sequence = dataset->newSequence(seq_name);
	sequence->next();
	cout << "DELETING Images from " << seq_name << endl;
	Query * query = new Query(*sequence, "DELETE FROM "+ dataset->getDataset() + ".intervals WHERE seqname='" + seq_name + "' AND imglocation='" +img_name +"';");
	cout << "OK: " << query->execute() << endl;
	delete (query);		
	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);
	*/

 // Create a value
	//JSONValue *value = new JSONValue(jsRoot);
	//print_out(value->Stringify().c_str());
}


