#pragma once

#include "client.h"
#include "sender_executor.h"

#include <saas/library/authorization/auth.h>
#include <saas/library/daemon_base/daemon/info.h>
#include <saas/library/daemon_base/daemon/controller.h>
#include <saas/library/http/multiserver.h>
#include <saas/util/destroyer.h>
#include <saas/library/flow/mirror.h>
#include <saas/indexerproxy/configs/config.h>
#include <saas/indexerproxy/export/subscriber.h>
#include <library/cpp/logger/global/global.h>

#include <library/cpp/http/server/http.h>

#include <util/generic/ptr.h>

class THttpProxyRTYServer: public THttpServer::ICallBack, public IMessageProcessor, public IServer {
private:
    const TProxyConfig& Config;
    TProxyWatchdogSubsciber WatchdogSubscriber;
    THolder<THttpMultiServer> Server;

    TDeferredMessagesQueue DeferredMessagesQueue;
    TDispatcher Dispatcher;
    NSaas::TAuthorization Authorizer;
    TStaticServiceMetrics Metrics;

    ISenderTask::TDestroyer Destroyer;
    TTaskExecutor Executor;
    NSaas::TKiwiExport Export;
    TFlowMirror FlowMirror;
    TWatchdogOptionsHandlePtr Watchdog;
public:
    typedef TProxyConfig TConfig;
    typedef TMessageCollectIndexerProxyInfo TInfoCollector;

public:
    TClientRequest* CreateClient() override;

    void ReopenLog() {
        Config.GetDispConfig().GetLog().ReopenLog();
        Config.GetDaemonConfig().ReopenLog();
    }

    void OnFailRequestEx(const TFailLogData& d) override {
        ERROR_LOG << "Request failed: " << d.failstate << " for url: " << d.url << Endl;
    }

    void OnException() override {
        try {
            throw;
        } catch (const yexception& e) {
            ERROR_LOG << "Exception occured in http server!!(" << e.what() << ")" << Endl;
        } catch (...) {
            ERROR_LOG << "Exception occured in http server!!" << Endl;
        }
    }

    void OnMaxConn() override {
        WARNING_LOG << "Connections count is maximum" << Endl;
    }

    void OnListenStart() override {
        INFO_LOG << "Listening started... OK" << Endl;
    }

    void OnListenStop() override {
        INFO_LOG << "Listening stopped... OK" << Endl;
    }

    void OnWait() override {
    }

    const TProxyConfig& GetConfig() const {
        return Config;
    }

    const TStaticServiceMetrics& GetMetrics() const {
        return Metrics;
    }

    TDeferredMessagesQueue& GetDeferredMessagesQueue() {
        return DeferredMessagesQueue;
    }

    THttpProxyRTYServer(const TProxyConfig& config);
    ~THttpProxyRTYServer();

    void Run() override;
    void Stop(ui32 rigidStopLevel = 0, const TCgiParameters* cgiParams = nullptr) override;
    //IMessageProcessor()
    virtual bool Process(IMessage* message) override;
    virtual TString Name() const override;
};

