#include <cstdlib>
#include <iostream>

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

/**
 * The CLI main function
 * You can follow the
 *
 * @param argc
 * @param argv
 * @return sucess
 */
int main(int argc, char** argv) {
    VTApi * vtapi = new VTApi(argc, argv);
    Dataset* dataset = vtapi->newDataset();
    dataset->next();
    //vtapi->commons->

    JSONObject jsRoot;




    Sequence* seq = dataset->newSequence();

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

            if (img->next()) {
                JSONObject picture;
                jsSeq[L"cover"] = new JSONValue(StringToWString(img->getDataLocation()));                
            }
            array.push_back(new JSONValue(jsSeq));
            
        } while (seq->next());
        jsRoot[L"sequences"] = new JSONValue(array);
    } else {
        jsRoot[L"sequences"] = new JSONValue(L"nodata");
    }

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

    delete (dataset);
    delete (vtapi);
}


