#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <memory>
#include <vector>

#include <TChain.h>

typedef std::filesystem::path Path;
typedef std::vector<Path> PathVector;

class DatasetExample
{
    public:
        DatasetExample(const PathVector& root_files) : tree(new TChain("Data_R"))
        {
            for( auto root_file: root_files )
            {
                tree->Add(root_file.c_str());
            }
            tree->SetBranchAddress("Channel", &channel, &b_channel);
            tree->SetBranchAddress("Timestamp", &timestamp, &b_timestamp);
            tree->SetBranchAddress("Board", &board, &b_board);
            tree->SetBranchAddress("Energy", &energy, &b_energy);
            tree->SetBranchAddress("Flags", &flags, &b_flags);
        }
        void WriteCSV(std::ostream& out) const
        {
            out << "Channel,Timestamp_ns,Energy,Flags\n";
            for(Long64_t entry = 0; tree->GetEntry(entry); ++entry)
            {
                tree->GetEntry(entry);
                out << channel << ',' << timestamp/1000 << ',' << energy << ',' << flags << '\n';
            }
        }
    private:
        const std::unique_ptr<TChain> tree;

        UShort_t channel;
        ULong64_t timestamp;
        UShort_t board;
        UShort_t energy;
        UInt_t flags;

        TBranch *b_channel;
        TBranch *b_timestamp;
        TBranch *b_board;
        TBranch *b_energy;
        TBranch *b_flags;
};


/// @brief Main entry point. Will write the dataset in CSV format to standard output.
/// @param argc The number of arguments.
/// @param argv Paths to existing .root files with list mode data.
int main(int argc, char** argv)
{
    if( 1 < argc )
    {
        PathVector root_files;
        for( int i = 1; i < argc; ++i)
        {
            root_files.push_back( argv[i] );
        }
        const DatasetExample example(root_files);
        example.WriteCSV(std::cout);
        return EXIT_SUCCESS;
    }
    else
    {
        std::cerr << "Usage error. Need at least one .root file.\n";
        return EXIT_FAILURE;
    }
}
