#include "split_by_pri_succ.h"
#include "log_parsers.h"
#include "aux_utils.h"

#include <util/string/builder.h>

namespace NH2Log {

    namespace {
        struct TPriSession : public TSession {
            bool Success = true;
        };
    }


    TVector<TPriSuccSessions> SplitByPriSucc(TFileManager& fileManager) {
        Y_H2_LOG_FUNC(fileManager);
        const TVector<TPriSuccSessions> outFiles{
            {fileManager.GetFileNameBySuffix("pri_fail"), false},
            {fileManager.GetFileNameBySuffix("pri_succ"), true}
        };

        THashMap<TString, TPriSession> active;
        TPriSession* sess = nullptr;
        TString line;
        while (fileManager.GetInput().ReadLine(line)) {
            if (!(sess = ParseNextLogLine(sess, active, line))) {
                continue;
            }

            auto& item = sess->Log.back();
            sess->Success &= !IsRecvPriFail(item);

            if (IsH2SessionEnd(item)) {
                DumpSession(sess->Log, fileManager.GetFileOutput(outFiles[sess->Success].FileName));
                active.erase(item.Addr);
            }
        }

        TVector<TPriSuccSessions> result;
        for (const auto& outFile : outFiles) {
            if (fileManager.ListFiles(outFile.FileName)) {
                result.emplace_back(outFile);
            }
        }

        return outFiles;
    }
}
