#pragma once

#include <wmconsole/version3/wmcutil/regex.h>
#include <wmconsole/version3/wmcutil/yt/yt_runner.h>
#include <wmconsole/version3/wmcutil/yt/yt_utils.h>

namespace NWebmaster {

struct TSourceTable {
    enum ETableFormat {
        E_FMT_CONVERTED_V4,
        E_FMT_USER_SESSIONS,
    };

    TSourceTable() = default;
    TSourceTable(const TString &name, ETableFormat format = E_FMT_CONVERTED_V4);

    int AgeDays() const;
    int AgeHours() const;
    bool IsDaily() const;

    bool operator<(const TSourceTable &rhs) const;

public:
    TString Name;
    TString NamePeriodBegin;
    TString NamePeriodEnd;
    time_t PeriodBegin = 0;
    time_t PeriodEnd = 0;
};

struct TSourceTablesForTarget {
    const char *ATTR_MOST_RECENT_SOURCE_NAME    = "most_recent_source";
    const char *ATTR_LEAST_RECENT_SOURCE_NAME   = "least_recent_source";

    TSourceTablesForTarget(NYT::IClientBasePtr client, size_t period, const TString &targetTable);
    TSourceTablesForTarget(NYT::IClientBasePtr client, const TSourceTablesForTarget &rhs, size_t period, const TString &targetTable);
    TSourceTablesForTarget(NYT::IClientBasePtr client, const TSourceTablesForTarget &rhs, const TString &targetTable);
    void Validate(NYT::IClientBasePtr client);
    bool NeedUpdate(NYT::IClientBasePtr client);
    void UpdateTarget(NYT::IClientBasePtr client);

public:
    TDeque<TSourceTable> Tables;
    unsigned Period = 0;
    TString TargetTable;
    TString LeastRecentSource;
    TString MostRecentSource;
    bool IsComplete = false;
    bool IsUpdated = false;
    int Lag = 0;
    int Holes = 0;
};

bool IsSourceTablesSetComplete(const TDeque<TSourceTable> &sourceTables, int &mostRecentSourceLag, int &holes);
bool LoadSourceTables(NYT::IClientBasePtr client, const TString &prefix, TDeque<TSourceTable> &sourceTables, int days, TSourceTable::ETableFormat format);
bool LoadConvertedTables(NYT::IClientBasePtr client, const TString &prefix, TDeque<TSourceTable> &sourceTables, int days = 100);
bool LoadUserSessions(NYT::IClientBasePtr client, const TString &prefix, TDeque<TSourceTable> &sourceTables, int days = 100);

} //namespace NWebmaster
