#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"
#include <climits>


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

/**
 * The CLI main function
 * You can follow the
 * ie. get_images alinary [image_per_page  page]
 *
 * @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);


    VTApi * vtapi = new VTApi(argc, argv);
    Dataset* dataset = vtapi->newDataset();
    dataset->next();
    //vtapi->commons->
    
    JSONObject jsRoot;
    JSONObject jsSeq;


    
    
    int img_per_page=INT_MAX;
    int page=0;
    if(argc>2){
	img_per_page= atoi (argv[2]);	
	page=atoi(argv[3]);
    }
	
    Sequence* seq = NULL;
    
    if ((seq=isIdExist(argv[1],dataset))!=NULL) {

	
        jsSeq[L"name"] = new JSONValue(StringToWString(seq->getName().c_str()));
        JSONArray array;
       
        //Image *img = seq->newImage();
	Image *img=seq->newImage();
	//img->setString("seqname",seq->getName());
	img->select = new Select(*img, "SELECT * FROM " + dataset->getDataset() + ".intervals WHERE seqname='"+ seq->getName() + "';"); 

	int i=0;
	for(i=0;i<img_per_page*page;i++)img->next();
	i=0;
        while (img->next()) {
            JSONObject picture;
            picture[L"path"]=new JSONValue(StringToWString(img->getDataLocation()));            
            array.push_back(new JSONValue(picture));
            i++;
	    if(i>=img_per_page) break;
        }
        jsSeq[L"imgs"] = new JSONValue(array);
	char buffer [33];
	sprintf(buffer,"%d",getImageCount(dataset,seq));
	jsSeq[L"image_count"] = new JSONValue(StringToWString(buffer));
        jsRoot[L"sequence"]=new JSONValue(jsSeq);
    }else{
        jsRoot[L"sequence"]=new JSONValue(L"nodata");
    }

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


