#include "memberpickerdialog.h"
#include <QDialogButtonBox>
#include <QLabel>
#include <QListWidget>
#include <QSet>
#include <QVBoxLayout>

MemberPickerDialog::MemberPickerDialog(const QString &title, QWidget *parent)
    : QDialog(parent)
{
  setWindowTitle(title);
  setMinimumWidth(300);

  auto *layout = new QVBoxLayout(this);

  m_list = new QListWidget(this);
  layout->addWidget(m_list);

  auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
  layout->addWidget(buttons);

  connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
  connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
}

void MemberPickerDialog::setMembers(const std::vector<Human> &members, const std::vector<QString> &exclude)
{
  m_list->clear();

  QSet<QString> excludeSet;
  for (const auto &e : exclude)
    excludeSet.insert(e);

  for (const auto &human : members)
  {
    if (excludeSet.contains(human.email))
      continue;
    auto *item = new QListWidgetItem(human.email, m_list);
    item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
    item->setCheckState(Qt::Unchecked);
    item->setData(Qt::UserRole, human.email);
  }
}

QStringList MemberPickerDialog::selectedEmails() const
{
  QStringList result;
  for (int i = 0; i < m_list->count(); ++i)
  {
    auto *item = m_list->item(i);
    if (item->checkState() == Qt::Checked)
      result.append(item->data(Qt::UserRole).toString());
  }
  return result;
}
