/*
 * SPDX-FileCopyrightText: 2004 Copyright contributors to the cppTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include <tango/server/AutoTangoMonitor.h>

#include <tango/server/DeviceImpl.h>
#include <tango/server/TangoMonitor.h>
#include <tango/server/Util.h>

namespace Tango
{

//---------------------------------------------------------------------------------------------------------------
//
// class :
//        AutoTangoMonitor
//
// description :
//        This class is only a helper class used to get a TangoMonitor object during its construction and to
//        it during its destruction. It makes developer life easier.
//
//---------------------------------------------------------------------------------------------------------------
AutoTangoMonitor::AutoTangoMonitor(Tango::DeviceImpl *dev, bool force)
{
    SerialModel ser = Util::instance()->get_serial_model();

    switch(ser)
    {
    case NO_SYNC:
        if(force)
        {
            mon = &(dev->only_one);
        }
        else
        {
            mon = nullptr;
        }
        break;

    case BY_DEVICE:
        mon = &(dev->only_one);
        break;

    case BY_CLASS:
        mon = &(dev->device_class->only_one);
        break;

    case BY_PROCESS:
        mon = &(Util::instance()->only_one);
        break;
    }
    if(mon != nullptr)
    {
        mon->get_monitor();
    }
}

AutoTangoMonitor::AutoTangoMonitor(Tango::DeviceClass *dev_cl)
{
    SerialModel ser = Util::instance()->get_serial_model();

    switch(ser)
    {
    case NO_SYNC:
    case BY_DEVICE:
        mon = nullptr;
        break;

    case BY_CLASS:
        mon = &(dev_cl->only_one);
        mon->get_monitor();
        break;

    case BY_PROCESS:
        mon = &(Util::instance()->only_one);
        mon->get_monitor();
        break;
    }
}

AutoTangoMonitor::AutoTangoMonitor(Tango::TangoMonitor *m) :
    mon(m)
{
    if(mon != nullptr)
    {
        mon->get_monitor();
    }
}

AutoTangoMonitor::~AutoTangoMonitor()
{
    if(mon != nullptr)
    {
        mon->rel_monitor();
    }
}

AutoTangoMonitor::AutoTangoMonitor(const std::shared_ptr<Tango::TangoMonitor> &m) :
    AutoTangoMonitor(m.get())
{
}

} // namespace Tango
