#include "control.h"

TRTYPoolsControl::TRTYPoolsControl() {
}

TRTYPoolsControl::~TRTYPoolsControl(){
}

void TRTYPoolsControl::Purge() {
    // Mutex must be locked
    std::remove_if(Updaters.begin(), Updaters.end(), [](TUpdater& u) {
        return !u.Handle.AsBase()->IsAlive() && !u.Handle.Lock()->AsBase()->IsAlive();
    });
}

void TRTYPoolsControl::Add(const TString& name, TUpdatableRef& handle) {
    with_lock(Mutex) {
        Updaters.push_back(TUpdater{name, handle});
        Purge();
    }
}

bool TRTYPoolsControl::Update(const TString& name, const TOptions& opts) {
    bool ok = true;
    bool needPurge = false;
    with_lock(Mutex) {
        for (auto& u : Updaters) {
            if (u.Name != name)
                continue;
            auto locked = u.Handle.Lock();
            if (!locked->AsBase()->IsAlive()) {
                needPurge = true;
                continue;
            }

            if (!locked->Get()->ResetOptions(opts)) {
                ok = false;
            }
        }

        if (needPurge) {
            Purge();
        }
    }
    return ok;
}


