/** Copyright (c) 2020-2023 The Creators of Simphone

    class ShowSeed (LoginDialog): display generated secret key

    See the file COPYING.LESSER.txt for copying permission.
**/

#include "showseed.h"
#include "ui_showseed.h"

#include "qtfix.h"
#include "simcore.h"

#include <QClipboard>
#include <QKeyEvent>

ShowSeed::ShowSeed(QWidget * parent, const QString & seed0, const QString & seed1)
  : Parent(parent), ui(new Ui::ShowSeed), m_format(0)
{
  ui->setupUi(this);
  QEvent event(QEvent::PaletteChange);
  changeEvent(&event);

  qtfix::fixPointSize(ui->seedLabel, font().pointSize());
  qtfix::fixPointSize(ui->textLabel, font().pointSize());
  qtfix::fixPointSize(ui->loginButton, font().pointSize());
  qtfix::fixCheckBoxIcon(ui->autoLoginBox, font());

  ui->textLabel->setText(qtfix::fixColorString(ui->textLabel->text(), SimParam::getColorString(true)));
  ui->autoLoginBox->setEnabled(!SimCore::mc_startupUser.isNull());
  //setWindowFlags(Qt::MSWindowsFixedSizeDialogHint);

  m_seed[0] = seed0;
  m_seed[1] = seed1;
  QString qs = getSeed(0);
  m_seedSize = qs.size() + qs.count('-');
  ui->seedLabel->setText(qs.toHtmlEscaped().replace('-', "-&#8203;"));
  ui->seedLabel->installEventFilter(this);
  ui->seedLabel->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(ui->seedLabel, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onCustomContextMenu(const QPoint &)));
#ifdef _DEBUG
  QApplication::clipboard()->setText(seed1);
#endif

  ui->label->setPixmap(QPixmap(":/welcome") /*.scaledToWidth(width() - 80, Qt::SmoothTransformation)*/);
  qtfix::fixMenuBar(ui->menubar, adjustToBiggerSize(), ui->verticalLayout);
}

ShowSeed::~ShowSeed()
{
  ui->seedLabel->removeEventFilter(this);
  delete ui;
  sim_audio_hangup_(0);
}

QString ShowSeed::getSeed(int format) const
{
  if (format) return m_seed[format];
  QStringList list = m_seed[format].split('-');
  for (int i = 0; i < list.size(); i++) {
    char c = *list[i].left(1).toUtf8().data();
    if (c >= 'a' && c <= 'z') c -= 'a' - 'A';
    list[i] = qApp->translate("SimCountry", (c + list[i].mid(1)).toUtf8().data()).split(' ').join("");
  }
  return list.join('-');
}

void ShowSeed::changeEvent(QEvent * event)
{
  switch (int(event->type())) {
    case QEvent::PaletteChange:
      if (qApp->styleSheet().isEmpty()) {
        QPalette p = QApplication::palette();
        p.setColor(QPalette::Inactive, QPalette::Highlight, p.color(QPalette::Active, QPalette::Highlight));
        p.setColor(QPalette::Inactive, QPalette::HighlightedText, p.color(QPalette::Active, QPalette::HighlightedText));
        ui->seedLabel->setPalette(p);
        prepareLanguage(ui->menuHelp, ui->actionEnglish, ui->actionFrench, ui->actionGerman);
      }
      break;

    case QEvent::LanguageChange:
      ui->retranslateUi(this);
      ui->label->setPixmap(QPixmap(":/welcome"));

      QString seed = getSeed(m_format);
      ui->seedLabel->setText(seed.toHtmlEscaped().replace('-', "-&#8203;"));
      m_seedSize = seed.size() + seed.count('-');
  }
  Parent::changeEvent(event);
}

void ShowSeed::on_formatButton_clicked()
{
  QString seed = getSeed(m_format = 1 - m_format);

  m_seedSize = seed.size() + seed.count('-');
  ui->seedLabel->setText(seed.toHtmlEscaped().replace('-', "-&#8203;"));
  SimParam::set("ui.login.countries", SimParam::get("ui.login.countries") ^ 3, false);
}

void ShowSeed::on_loginButton_clicked()
{
  done(QDialog::Accepted + (SimCore::mc_startupUser.isNull() || ui->autoLoginBox->isChecked()));
}

void ShowSeed::on_actionEnglish_triggered()
{
  Parent::on_actionEnglish_triggered(ui->actionEnglish, ui->actionFrench, ui->actionGerman);
}

void ShowSeed::on_actionFrench_triggered()
{
  Parent::on_actionFrench_triggered(ui->actionEnglish, ui->actionFrench, ui->actionGerman);
}

void ShowSeed::on_actionGerman_triggered()
{
  Parent::on_actionGerman_triggered(ui->actionEnglish, ui->actionFrench, ui->actionGerman);
}

void ShowSeed::onCustomContextMenu(const QPoint & pos)
{
  QMenu menu(this);
  QAction * c = menu.addAction(qApp->translate("QWidgetTextControl", "&Copy"));
  menu.addSeparator();
  QAction * s = menu.addAction(tr("Select &All"));

  c->setShortcut(Qt::CTRL + Qt::Key_C);
  s->setShortcut(Qt::CTRL + Qt::Key_A);
  if (!ui->seedLabel->hasSelectedText()) c->setEnabled(false);
  if (QAction * a = menu.exec(ui->seedLabel->mapToGlobal(pos))) {
    if (a == c) {
      QApplication::clipboard()->setText(ui->seedLabel->selectedText().replace(QChar(0x200b), ""));
    } else if (a == s) {
      ui->seedLabel->setSelection(0, m_seedSize);
    }
  }
}

bool ShowSeed::eventFilter(QObject * obj, QEvent * event)
{
  if (event->type() == QEvent::KeyPress) {
    QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);

    if (keyEvent->matches(QKeySequence::Copy) ||
        (keyEvent->modifiers() & Qt::ControlModifier && keyEvent->key() == Qt::Key_C)) {
      QApplication::clipboard()->setText(ui->seedLabel->selectedText().replace(QChar(0x200b), ""));
      return true;
    }
  }
  return Parent::eventFilter(obj, event);
}
