#include "RenameRemote.h"
#include <QTabWidget>
#include <QValidator>

// Used to validate potential new names for a remote. Doesn't allow double
// quote characters in the name, doesn't allow duplicate names from tabs
// other than the one being renamed.
//
class ValidateRemoteName : public QValidator {
public:

   ValidateRemoteName(QTabWidget * init_tabwid,
                      int          init_curtab,
                      QObject    * parent = 0);

   virtual
   ~ValidateRemoteName();

   virtual void
   fixup(QString & input) const;

   virtual QValidator::State
   validate(QString & input, int & pos) const;

private:

   int          curtab;
   QTabWidget * tabwid;
};

RenameRemote::RenameRemote(QWidget * parent, Qt::WindowFlags f)
 : QDialog(parent, f) {

   ui.setupUi(this);
}

RenameRemote::~RenameRemote() {
}

void
RenameRemote::doRenameTab(QTabWidget * tabwid) {
   int curtab = tabwid->currentIndex();
   ValidateRemoteName vrn(tabwid, curtab);
   ui.remoteNameEdit->setValidator(&vrn);
   ui.remoteNameEdit->setText(tabwid->tabText(curtab));
   ui.remoteNameEdit->selectAll();
   ui.remoteNameEdit->setFocus();
   int exec_stat = exec();
   ui.remoteNameEdit->setValidator(NULL);
   if (exec_stat == QDialog::Accepted) {
      QString newname = ui.remoteNameEdit->text();
      if (! newname.isEmpty()) {
         tabwid->setTabText(curtab, newname);
      }
   }
}

ValidateRemoteName::ValidateRemoteName(
   QTabWidget * init_tabwid,
   int init_curtab,
   QObject * parent)
 : QValidator(parent),
   curtab(init_curtab),
   tabwid(init_tabwid) {

   return;
}

ValidateRemoteName::~ValidateRemoteName() {
   return;
}

void
ValidateRemoteName::fixup(QString & input) const {
   QString basename = input;
   int tabs = tabwid->count() + 1;
   for (int i = 2; i < tabs; ++i) {
      QString testname = basename;
      testname.append(QString("<%1>").arg(i));
      int dummy;
      if (validate(testname, dummy) == QValidator::Acceptable) {
         input = testname;
         return;
      }
   }
}

QValidator::State
ValidateRemoteName::validate(QString & input, int & /* pos */) const {

   // Double quotes will mess up my simplistic xml writer, disallow them

   if (input.contains('\"')) {
      return QValidator::Invalid;
   }

   // Don't want remotes with duplicate names, report Intermediate for
   // a duplicate name (since user could type more to make the name unique).

   int tabs = tabwid->count();
   for (int i = 0; i < tabs; ++i) {
      if (i != curtab) {
         if (input == tabwid->tabText(i)) {
            return QValidator::Intermediate;
         }
      }
   }

   // Don't want empty name either, report Intermediate for that as well

   if (input.isEmpty()) {
      return QValidator::Intermediate;
   }

   // Otherwise, I guess this name is OK.

   return QValidator::Acceptable;
}
