/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>
#include <QHBoxLayout>
#include <QRadioButton>

#include "MvQBoolLine.h"

#include "LineFactory.h"
#include "RequestPanel.h"
#include "MvIconParameter.h"

MvQBoolLine::MvQBoolLine(RequestPanel& owner, const MvIconParameter& param) :
    MvQRequestPanelLine(owner, param)
{
    radioParent_ = new QWidget(parentWidget_);
    layout_ = new QHBoxLayout();
    layout_->setSpacing(0);
    layout_->setContentsMargins(1, 1, 1, 1);

    radioParent_->setLayout(layout_);
    owner_.addWidget(radioParent_, row_, WidgetColumn);

    QString strOnVal = "On";
    QString strOffVal = "Off";

    // Radio buttons
    radioOn_ = new QRadioButton(strOnVal, radioParent_);
    radioOff_ = new QRadioButton(strOffVal, radioParent_);
    layout_->addWidget(radioOn_);
    layout_->addWidget(radioOff_, 1);

    connect(radioOn_, SIGNAL(toggled(bool)),
            this, SLOT(slotStatusChanged(bool)));
}

MvQBoolLine::~MvQBoolLine() = default;

void MvQBoolLine::refresh(const std::vector<std::string>& values)
{
    // We need to set both radio buttons because before the event loop
    // is started the autoexclusive feature does not work!
    if (values.size() > 0) {
        char c = values[0][1];  //== ON or on
        if (c == 'N' || c == 'n') {
            radioOn_->setChecked(true);
            if (radioOff_->isChecked())
                radioOff_->setChecked(false);
        }
        else {
            radioOn_->setChecked(false);
            if (!radioOff_->isChecked())
                radioOff_->setChecked(true);
        }
    }

    // changed_ = false;
}

void MvQBoolLine::slotStatusChanged(bool)
{
    owner_.set(param_.name(), (radioOn_->isChecked()) ? "on" : "off");
}

static LineMaker<MvQBoolLine> maker1("on_off");
