#include "createstreamdialog.h"
#include <QComboBox>
#include <QDialogButtonBox>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QVBoxLayout>

CreateStreamDialog::CreateStreamDialog(QWidget *parent)
    : QDialog(parent)
{
  setWindowTitle("New Stream");
  setMinimumWidth(320);

  auto *layout = new QVBoxLayout(this);

  layout->addWidget(new QLabel("Stream name:"));
  m_nameEdit = new QLineEdit(this);
  m_nameEdit->setPlaceholderText("e.g. design-review");
  layout->addWidget(m_nameEdit);

  layout->addWidget(new QLabel("Visibility:"));
  m_visibilityCombo = new QComboBox(this);
  m_visibilityCombo->addItem("Everyone in network", "network_all");
  m_visibilityCombo->addItem("Specific members", "custom");
  layout->addWidget(m_visibilityCombo);

  m_membersLabel = new QLabel("Select members:");
  m_membersList = new QListWidget(this);
  m_membersLabel->setVisible(false);
  m_membersList->setVisible(false);
  layout->addWidget(m_membersLabel);
  layout->addWidget(m_membersList);

  connect(m_visibilityCombo, &QComboBox::currentIndexChanged, this, [this](int) {
    bool specific = (m_visibilityCombo->currentData().toString() == "custom");
    m_membersLabel->setVisible(specific);
    m_membersList->setVisible(specific);
  });

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

  connect(buttons, &QDialogButtonBox::accepted, this, [this]() {
    QString name = m_nameEdit->text().trimmed();
    if (name.isEmpty())
      return;

    QString visibility = m_visibilityCombo->currentData().toString();
    QStringList members;
    if (visibility == "custom")
    {
      for (int i = 0; i < m_membersList->count(); ++i)
      {
        auto *item = m_membersList->item(i);
        if (item->checkState() == Qt::Checked)
          members.append(item->data(Qt::UserRole).toString());
      }
    }

    emit streamRequested(name, visibility, members);
    m_nameEdit->clear();
    m_visibilityCombo->setCurrentIndex(0);
    accept();
  });

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

void CreateStreamDialog::setNetworkMembers(const std::vector<Human> &members)
{
  m_membersList->clear();
  for (const auto &human : members)
  {
    auto *item = new QListWidgetItem(human.email, m_membersList);
    item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
    item->setCheckState(Qt::Unchecked);
    item->setData(Qt::UserRole, human.email);
  }
}
