#include "main.h"

#include <library/cpp/getopt/opt.h>
#include <mapreduce/yt/interface/client.h>
#include <util/folder/path.h>

using NLastGetopt::TOpt;
using NLastGetopt::TOpts;
using NLastGetopt::TOptsParseResult;

void RunMain(int argc, const char** argv) {
    NYT::Initialize(argc, argv);

    TString pcapFile;
    TString outputDir;
    int depth;
    bool ytUse;
    TString ytTable;
    TString ytCluster;

    TOpts opts = TOpts::Default();
    opts.AddLongOption('r', "read-file", "input pcap").StoreResult(&pcapFile).RequiredArgument().Required();
    opts.AddLongOption('o', "output-dir", "output dir").StoreResult(&outputDir).RequiredArgument();
    opts.AddLongOption('d', "depth", "file path depth").StoreResult(&depth).RequiredArgument().DefaultValue(0);
    opts.AddLongOption("yt", "write to yt").SetFlag(&ytUse).NoArgument();
    opts.AddLongOption('t', "table", "table name").StoreResult(&ytTable).RequiredArgument();
    opts.AddLongOption('c', "cluster", "cluster name").StoreResult(&ytCluster).RequiredArgument().DefaultValue("hahn");

    TOptsParseResult res(&opts, argc, argv);

    TFsPath pcapFileCheck(pcapFile);
    if (!pcapFileCheck.IsFile()) {
        ythrow yexception() << "Incorrect pcap file\n";
    }

    if (ytUse && ytTable.empty()) {
        ythrow yexception() << "Empty table name\n";
    }

    if (ytUse && ytCluster.empty()) {
        ythrow yexception() << "Empty cluster name\n";
    }

    if (ytUse)
        RunYtSplitter(pcapFile, ytCluster, ytTable);
    else
        RunFileSplitter(pcapFile, outputDir, depth);
}

int main(int argc, const char** argv) noexcept {
    try {
        RunMain(argc, argv);
    } catch (const yexception& e) {
        Cerr << e.what() << "\n";
        return 1;
    } catch (...) {
        return 1;
    }
}
