#include "showhidewidget.h"
#include <QtWidgets>

ShowHideWidget::ShowHideWidget(QWidget *parent) :
    QWidget(parent)
{
    createButtons();
    layoutInterface();
}


//
// Public Functions
//
void ShowHideWidget::setCategories(QStringList c)
{
    myCategories = c;
    clearList();
    createButtons();
    setupList();
    layoutInterface();
}

QStringList ShowHideWidget::categories() const
{
    return myCategories;
}


//
// Private Slots
//
void ShowHideWidget::showAll()
{
    foreach (QCheckBox *box, categoryCheckBoxList) {
        // If they are not first unchecked, if a box
        // is unchecked in the row, but the all box is
        // checked, they will not all become checked.
        box->setChecked(false);
        box->setChecked(true);
    }
}

void ShowHideWidget::hideAll()
{
    foreach (QCheckBox *box, categoryCheckBoxList) {
        box->setChecked(true);
        box->setChecked(false);
    }
}

void ShowHideWidget::checkBoxClicked(bool isChecked)
{
    QCheckBox *box = qobject_cast<QCheckBox*>(sender());
    if (box) {
        int id;
        for (int i = 0; i < checkBoxList.length(); i++) {
            if (box == checkBoxList.at(i)) {
                id = i;
                break;
            }
        }
        emit buttonToggled(id, isChecked);
    }
}

//
// Private Functions
//
void ShowHideWidget::createButtons()
{
    showAllButton = new QPushButton(tr("Show All"));
    connect(showAllButton, SIGNAL(clicked()), this, SLOT(showAll()));
    hideAllButton = new QPushButton(tr("Hide All"));
    connect(hideAllButton, SIGNAL(clicked()), this, SLOT(hideAll()));

    buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(showAllButton);
    buttonLayout->addWidget(hideAllButton);
}

void ShowHideWidget::clearList()
{
    rows.clear();
    delete layout();
    qDeleteAll(children());
}

void ShowHideWidget::setupList()
{
    QStringList uniqueCategories = myCategories;
    uniqueCategories.removeDuplicates();

    for (int i = 0; i < uniqueCategories.length(); i++) {
        QHBoxLayout *layout = new QHBoxLayout;
        QCheckBox *box = new QCheckBox(tr("All %1").arg(uniqueCategories.at(i)));
        categoryCheckBoxList << box;
        layout->addWidget(box);
        rows << layout;
    }

    for (int i = 0; i < myCategories.length(); i++) {
        int index = uniqueCategories.indexOf(myCategories.at(i));
        QCheckBox *box = new QCheckBox;
        connect(box, SIGNAL(toggled(bool)), this, SLOT(checkBoxClicked(bool)));
        connect(categoryCheckBoxList.at(index), SIGNAL(toggled(bool)), box, SLOT(setChecked(bool)));
        checkBoxList << box;
        rows.at(index)->addWidget(box);
    }

    for (int i = 0; i < rows.length(); i++)
        rows.at(i)->addStretch();
}

void ShowHideWidget::layoutInterface()
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(buttonLayout);
    foreach (QHBoxLayout *layout, rows)
        mainLayout->addLayout(layout);
    setLayout(mainLayout);
}

