#include "server.h"

#include <saas/util/queue.h>

namespace NRTY {
    TClientRequest* TServer::CreateClient() {
        return new NRTY::TClient(Metrics, Processors);
    }

    TServer::TServer(const NRTY::TConfig& config)
        : Config(config)
        , Metrics(&GetGlobalMetrics(), "")
        , Processors(config.GetProcessorsConfig())
    {
        Server.Reset(new THttpServer(this, Config.GetHttpOptionsConfig()));
    }

    void TServer::Stop(ui32 /*rigidStopLevel*/, const TCgiParameters* /*cgiParams*/) {
        UnregisterGlobalMessageProcessor(this);
        INFO_LOG << "HttpServer stopping..." << Endl;
        Server->Stop();
        Server->Wait();
        INFO_LOG << "HttpServer stopping...OK" << Endl;
        INFO_LOG << "Processors stopping..." << Endl;
        Processors.Stop();
        INFO_LOG << "Processors stopping...OK" << Endl;
    }

    void TServer::Run() {
        INFO_LOG << "Processors starting..." << Endl;
        Processors.Start();
        INFO_LOG << "Processors starting...OK" << Endl;
        INFO_LOG << "HTTP server starting..." << Endl;
        VERIFY_WITH_LOG(Server->Start(), "Server can't start");
        INFO_LOG << "HTTP server starting... OK" << Endl;
        RegisterGlobalMessageProcessor(this);
    }

    bool TServer::Process(IMessage* message) {
        TMessageCollectCrawlerInfo* mci = dynamic_cast<TMessageCollectCrawlerInfo*>(message);
        if (mci) {
            return true;
        }
        return false;
    }

    TString TServer::Name() const {
        return "ProcessorsServer";
    }
}
