/*
 * SPDX-FileCopyrightText: 2000-2002 Copyright LifeLine Networks BV (www.lifeline.nl)
 * SPDX-FileCopyrightText: 2000-2002 Copyright Bastiaan Bakker
 * SPDX-FileCopyrightText: 2004 Copyright contributors to the cppTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include <tango/common/log4tango/AppenderAttachable.h>

#include <tango/common/log4tango/Portability.h>

#include <mutex>

namespace log4tango
{

AppenderAttachable::AppenderAttachable()
{
    // no-op ctor.
}

AppenderAttachable::~AppenderAttachable()
{
    remove_all_appenders();
}

void AppenderAttachable::add_appender(Appender *appender)
{
    if(appender != nullptr)
    {
        std::scoped_lock guard{_appendersMutex};
        _appenders.emplace(appender->get_name(), appender);
    }
}

AppenderList AppenderAttachable::get_all_appenders()
{
    std::scoped_lock guard{_appendersMutex};
    AppenderList al(0);
    auto it = _appenders.begin();
    auto end = _appenders.end();
    for(; it != end; ++it)
    {
        al.push_back(it->second);
    }
    return al;
}

Appender *AppenderAttachable::get_appender(const std::string &name)
{
    std::scoped_lock guard{_appendersMutex};
    auto it = _appenders.find(name);
    if(it != _appenders.end())
    {
        return it->second;
    }
    return nullptr;
}

bool AppenderAttachable::is_attached(Appender *appender)
{
    std::scoped_lock guard{_appendersMutex};
    return (appender != nullptr) && _appenders.find(appender->get_name()) != _appenders.end();
}

void AppenderAttachable::remove_all_appenders()
{
    std::scoped_lock guard{_appendersMutex};
    auto it = _appenders.begin();
    auto end = _appenders.end();
    for(; it != end; ++it)
    {
        delete it->second;
    }
    _appenders.clear();
}

void AppenderAttachable::remove_appender(Appender *appender)
{
    if(appender != nullptr)
    {
        remove_appender(appender->get_name());
    }
}

void AppenderAttachable::remove_appender(const std::string &name)
{
    std::scoped_lock guard{_appendersMutex};
    auto it = _appenders.find(name);
    if(it != _appenders.end())
    {
        delete it->second;
        _appenders.erase(it);
    }
}

} // namespace log4tango
