#include <util/thread/singleton.h>
#include "master_main.h"
#include "master_process.h"
#include "main_event_handler.h"

using namespace NConfig;

namespace NSrvKernel::NProcessCore {
    TStatsCallback::TStatsCallback(TSharedCounter& connectionsCounter, const TMainConfig& mainConfig,
        TContExecutor& executor, TSharedStatsManager& statsManager, TMasterProcess& masterProcess, TSystemLog& log)
        : ConnectionsCounter(connectionsCounter)
        , BufferSize(mainConfig.Buffer)
        , Executor(executor)
        , Log(log)
        , MasterProcess(masterProcess)
        , MaxStatsConnections_(mainConfig.MaxStatsConnections)
        , StatsManager_(statsManager)
    {}

    void TStatsCallback::OnAcceptFull(const TAcceptFull& acc) {
        if (MaxStatsConnections_) {
            while (InProgr >= MaxStatsConnections_) {
                StatsConnections_.PopFront()->Cancel();
            }
        }

        StatsConnections_.PushBack(new TStatsConnection(this, acc, StatsManager_, MasterProcess));
    }

    void TStatsCallback::OnError() {
        Log << "on error: " << CurrentExceptionMessage() << Endl;
    }

    void TStatsCallback::OnStop(TSocketHolder* s) {
        s->ShutDown(SHUT_RDWR);
        s->Close();
    }

    TAdminCallback::TAdminCallback(TSharedCounter& connectionsCounter, const TMainConfig& mainConfig,
        TContExecutor& executor, TMasterProcess& masterProcess, TMainTask& mainTask, TSystemLog& log)
        : ConnectionsCounter(connectionsCounter)
        , BufferSize(mainConfig.Buffer)
        , Executor(executor)
        , Log(log)
        , MasterProcess(masterProcess)
        , MainTask(mainTask)
        , MaxAdminConnections_(mainConfig.MaxAdminConnections)
        , AdminManager_(masterProcess)
    {}

    void TAdminCallback::OnAcceptFull(const TAcceptFull& acc) {
        if (MaxAdminConnections_) {
            while (InProgr >= MaxAdminConnections_) {
                AdminConnections_.PopFront()->Cancel();
            }
        }

        AdminConnections_.PushBack(new TAdminConnection(this, acc, AdminManager_));
    }

    void TAdminCallback::OnError() {
        Log << "on error: " << CurrentExceptionMessage() << Endl;
    }

    void TAdminCallback::OnStop(TSocketHolder* s) {
        s->ShutDown(SHUT_RDWR);
        s->Close();
    }
}
