#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 IntToWString(const int i) {
    char buff[30];
    sprintf(buff,"%i",i);
    int len = strlen(buff);
    wchar_t* buf = new wchar_t[len];
    size_t num_chars = mbstowcs(buf, buff, len);
    std::wstring temp(buf, num_chars);
    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;
}


/**
 *
 * @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_tags_from_sequence.log","w",stdout);

    JSONObject jsRoot;
    JSONObject jsSeq;
    

    if(argc==4){    
	    VTApi * vtapi = new VTApi(argc, argv);
	    Dataset* dataset = vtapi->newDataset();
	    dataset->next();
    	    Sequence* seq = dataset->newSequence(argv[1]);

	    if (seq->next()) {
		printf("seq %s\n",seq->getName().c_str());
		JSONArray img_array;       
		Image *img=seq->newImage();
		destruct(img->select);
	 
		img->select = new Select(*img);
		img->select->limit=atoi(argv[3]);
		img->select->offset=atoi(argv[2]);
	  	img->select->whereString("seqname", seq->getName());
	 	img->select->from("intervals","imglocation");
	 	img->select->from("intervals","tags");

		int idx=0;
		while(img->next()){	
			printf("image %s\n",img->getLocation().c_str());
			JSONObject jsImg;

			string t=string("tags");
			int count;
			int *tags=img->getIntA(t,count);

			JSONArray tag_array;
			for(int i=0;i<count;i++){
				tag_array.push_back(new JSONValue(IntToWString(tags[i])));
			}
			jsImg[L"tags"]=new JSONValue(tag_array);

			jsImg[L"name"]=new JSONValue(StringToWString(img->getLocation()));
			img_array.push_back(new JSONValue(jsImg));		
			idx++;
			//if(idx>10)break;
		}
		jsSeq[L"name"] = new JSONValue(StringToWString(seq->getName().c_str()));
		jsSeq[L"imgs"]=new JSONValue(img_array);	
		jsRoot[L"sequence"]=new JSONValue(jsSeq);
		destruct(img->select);
		delete(img);

	    }else{
		jsRoot[L"sequence"]=new JSONValue(L"nodata");
	    }
	    delete (dataset);
	    delete (vtapi);
    }else{
	jsRoot[L"error"]=new JSONValue(L"param error! using program seqname offset limit");
    }

    fflush(stdout);
    dup2(fd, fileno(stdout));
    close(fd);
    clearerr(stdout);
    fsetpos(stdout, &pos);

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


