#include "touchbuttframe.h"

TouchButtFrame::TouchButtFrame(QWidget *parent, QColor cr, QColor cg, QColor cw, QColor cp, Qt::Orientation orientation) :
    QFrame(parent)
{
    colr = cr; colg = cg; colw = cw; colp = cp;
    setFrameShape(QFrame::StyledPanel);
    lay = new QBoxLayout(QBoxLayout::LeftToRight);
    lay->setContentsMargins(0,0,0,0);
    if (orientation == Qt::Vertical) lay->setDirection(QBoxLayout::TopToBottom);
}


void TouchButtFrame::addButton(const QString &caption)
{
        touch_butt * butt = new touch_butt(lay->count(),caption,colr,colg,colw,colp);
        butt->setMinimumHeight(50);
        butt->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
        butt->setCheckable(true);
        butt->setAutoExclusive(true);
        butt->setAutoFillBackground(true);
        lay->addWidget(butt);
        this->setLayout(lay);
        connect(butt,SIGNAL(touch_click(int)),SLOT(butt_click(int)));
        connect(butt,SIGNAL(touch_toggle(int,bool)),SLOT(butt_toggle(int,bool)));
}


void TouchButtFrame::butt_click(int index)
{
        emit click(index);
}


void TouchButtFrame::butt_toggle(int index,bool checked)
{
        emit toggle(index,checked);
}


void TouchButtFrame::resetColors()
{
    for (int i=0; i<lay->count(); ++i)
    {
        Button(i)->setColor(colr,colg,colw,colp);
    }
}


void TouchButtFrame::deleteButtons()
{
    while (!lay->isEmpty())
        delete Button(0);
}


void TouchButtFrame::setButtons(const QStringList &captions)
{
    int cur = currentButton();
    deleteButtons();
    for (int i=0; i<captions.size(); ++i)
    {
        addButton(captions.at(i));
    }
    if (Button(cur) != 0) Button(cur)->setChecked(true);
    else if (!captions.isEmpty()) Button(0)->setChecked(true);
}


void TouchButtFrame::setCurrentButton(int index)
{
     if (Button(index) != 0)
     {
         if (currentButton() != -1) Button(currentButton())->setChecked(false);
         Button(index)->setChecked(true);
     }
}


int TouchButtFrame::currentButton()
{
     for (int i=0; i<buttCount(); ++i)
         if (Button(i)->isChecked()) return i;
     return -1;
}


QStringList TouchButtFrame::buttons()
{
    QStringList l;
    for (int i=0; i<lay->count(); ++i)
        l.append(Button(i)->text());
    return l;
}


touch_butt * TouchButtFrame::Button(int index)
{
    if (index >= 0 && index < lay->count())
        return (qobject_cast<touch_butt*>(lay->itemAt(index)->widget()));
    else return 0;
}
