#include "MateChooser.h"
#include "ui_MateChooser.h"
#include "DataObject/ComdObject.h"
#include <QTreeWidgetItem>

MateChooser::MateChooser(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MateChooser)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags()|Qt::FramelessWindowHint);
    setAttribute(Qt::WA_PaintOnScreen);
    setAttribute(Qt::WA_QuitOnClose, false);
    _group.setExclusive(false);
    connect(&_group, SIGNAL(buttonClicked(QAbstractButton*)), SLOT(onMateItemClicked(QAbstractButton*)));
}

MateChooser::~MateChooser()
{
    delete ui;
}

void MateChooser::setTitle(const QString &t)
{
    ui->mateTitle->setText(t);
}

QString MateChooser::getTitle() const
{
    return ui->mateTitle->text();
}

QList<ComdObject *> MateChooser::candidates()
{
    QList<ComdObject *> list;
    QStringList keys = _candidates_map.keys();
    foreach(QString k, keys) {
        list << _candidates_map[k];
    }

    return list;
}

void MateChooser::setMates(const QList<ComdObject*> &pendingMates, QList<ComdObject*> &assignedMates)
{
    _selected_mates = assignedMates;
    foreach(ComdObject *amo, assignedMates) {
        _candidates_map[amo->name] = amo;
    }

    foreach(ComdObject *mo, pendingMates) {
        if (!_candidates_map.contains(mo->name)) {
            _candidates_map[mo->name] = mo;
        }
    }

    int row = 0, col = 0;
    _group.buttons().clear();
    QStringList keys = _candidates_map.keys();
    foreach(QString k, keys) {
        ComdObject *mate = _candidates_map[k];
        QPushButton *mate_btn = new QPushButton(mate->name);
        mate_btn->setFocusPolicy(Qt::NoFocus);
        mate_btn->setCheckable(true);

        if (_selected_mates.contains(mate)) {
            mate_btn->setChecked(true);
        }
        mate_btn->setMinimumSize(60, 40);
        mate_btn->setMaximumSize(60, 40);
        ui->mateList->addWidget(mate_btn, row, col);
        _group.addButton(mate_btn);
        ++col;
        if (col > 2) {
            ++row;
            col = 0;
        }
    }
}

QList<ComdObject *>  MateChooser::selectedMates() const
{
    if (this->result() == QDialog::Accepted) {
        return _selected_mates;
    }
    else {
        return QList<ComdObject*>();
    }
}

void MateChooser::on_mateCancel_clicked()
{
    QDialog::reject();
}

void MateChooser::on_mateConfirm_clicked()
{
    QDialog::accept();
}

void MateChooser::onMateItemClicked(QAbstractButton *item)
{
    if (item->isChecked()) {
        _selected_mates << _candidates_map[item->text()];
    }
    else {
        _selected_mates.removeOne(_candidates_map[item->text()]);
    }
}
