#include <iostream>
#include "temporaltree.h"
#include "nlohmann/json.hpp"
#include "util.h"
#include "treejsonreader.h"
#include "treewriter.h"

char *getCmdOption(char **begin, char **end, const std::string &option)
{
    char **itr = std::find(begin, end, option);
    if (itr != end && ++itr != end)
    {
        return *itr;
    }
    return 0;
}

bool cmdOptionExists(char **begin, char **end, const std::string &option)
{
    return std::find(begin, end, option) != end;
}

int main(int argc, char *argv[])
{
    // TemporalTreeJSONReaderNTG* tr = new TemporalTreeJSONReaderNTG();
    // auto treepointer = tr->readData("../data/trees/ViscousFingers.ntg");

    string filein(getCmdOption(argv, argv + argc, "-fin"));
    string fileout(getCmdOption(argv, argv + argc, "-fout"));
    string numtimess(getCmdOption(argv, argv + argc, "-times"));

    int numtimes = stoi(numtimess);

    shared_ptr<TemporalTree> treepointer;

    if (hasEnding(filein, ".tree"))
    {
        TemporalTreeJSONReader *tr = new TemporalTreeJSONReader();
        treepointer = tr->readData(filein);
    }
    else
    {
        TemporalTreeJSONReaderNTG *tr = new TemporalTreeJSONReaderNTG();
        treepointer = tr->readData(filein);
    }

    TemporalTree inTree = treepointer->getSelfDeaggregated();

    auto times = inTree.getTimes();
    vector<size_t> vtimes(times.begin(), times.end());

    
    for (int i = 0; i < vtimes.size(); i+=20) {
        if (i+numtimes-1 >= vtimes.size()) break;

        TemporalTree outTree = inTree.getFromTimeFrame(vtimes[i], vtimes[i+numtimes-1]);

        TemporalTreeWriter writer;
        writer.portInTree = make_shared<TemporalTree>(outTree);
        writer.propFilename = fileout + to_string(vtimes[i]) + "_" + to_string(vtimes[i+numtimes-1]) + ".tree";
        writer.process();
    }

    return 0;
}