#pragma once

#include "dolbilka_plan.h"
#include "http_helper.h"
#include "model.h"
#include "util.h"
#include "globals.h"

#include <library/cpp/getoptpb/getoptpb.h>


using namespace NSaas;

namespace NRTYServer {

class TQueryOpBase: public IRtyOp {
public:
    using TPlan = TVector<TDolbilkaPlan::TQueryData>;

protected:
    TRtyOpContext OpCtx;
    THolder<TNetworkAddress> EndPoint;
    TVector<TString> Plan;

public:
    void WaitForSearcherStart();

    ui32 DoQuery(const TString& query, TString* resultBuf);

    virtual void Init(IRtyOpHost& host) override;

    virtual void Prepare() override;

    void LoadPlan(TPlan& plan, const TRtyOpsConfig& config, ui32 maxItemsToRead);

    static void PatchQueries(TVector<TDolbilkaPlan::TQueryData>& plan, const TString& extraCgi);

    void DebugRetryAsText(const TDolbilkaPlan::TQueryData& req);

protected:
    template <typename TProto>
    static TProto GetExtraParams(TString virtualArgs) {
        int argc;
        const char** argv;
        TVirtualArgs va(virtualArgs);
        va.GetArgs(argc, argv);
        TProto result;
        TString errorMsg;
        NGetoptPb::TGetoptPbSettings goSettings;
        goSettings.DumpConfig = false;
        if (!NGetoptPb::GetoptPb(argc, argv, result, errorMsg, goSettings)) {
            ythrow yexception() << "Failed to parse VirtualArgs, error: " << errorMsg << Endl;
        };
        return result;
    }
};


}
