/*
 * This file is part of the xTuple ERP: PostBooks Edition, a free and
 * open source Enterprise Resource Planning software suite,
 * Copyright (c) 1999-2009 by OpenMFG LLC, d/b/a xTuple.
 * It is licensed to you under the Common Public Attribution License
 * version 1.0, the full text of which (including xTuple-specific Exhibits)
 * is available at www.xtuple.com/CPAL.  By using this software, you agree
 * to be bound by its terms.
 */

#include "hotkey.h"

#include <QVariant>
#include <QMessageBox>

/*
 *  Constructs a hotkey as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  true to construct a modal dialog.
 */
hotkey::hotkey(QWidget* parent, const char* name, bool modal, Qt::WFlags fl)
    : XDialog(parent, name, modal, fl)
{
  setupUi(this);

  // signals and slots connections
  connect(_close, SIGNAL(clicked()), this, SLOT(reject()));
  connect(_save, SIGNAL(clicked()), this, SLOT(sSave()));

  _hotkey->insertItem("F1");
  _hotkey->insertItem("F2");
  _hotkey->insertItem("F3");
  _hotkey->insertItem("F4");
  _hotkey->insertItem("F5");
  _hotkey->insertItem("F6");
  _hotkey->insertItem("F7");
  _hotkey->insertItem("F8");
  _hotkey->insertItem("F9");
  _hotkey->insertItem("Ctrl+B");
  _hotkey->insertItem("Ctrl+C");
  _hotkey->insertItem("Ctrl+D");
  _hotkey->insertItem("Ctrl+E");
  _hotkey->insertItem("Ctrl+F");
  _hotkey->insertItem("Ctrl+G");
  _hotkey->insertItem("Ctrl+H");
  _hotkey->insertItem("Ctrl+I");
  _hotkey->insertItem("Ctrl+J");
  _hotkey->insertItem("Ctrl+K");
  _hotkey->insertItem("Ctrl+M");
  _hotkey->insertItem("Ctrl+N");
  _hotkey->insertItem("Ctrl+O");
  _hotkey->insertItem("Ctrl+P");
  _hotkey->insertItem("Ctrl+Q");
  _hotkey->insertItem("Ctrl+R");
  _hotkey->insertItem("Ctrl+T");
  _hotkey->insertItem("Ctrl+U");
  _hotkey->insertItem("Ctrl+V");
  _hotkey->insertItem("Ctrl+W");
  _hotkey->insertItem("Ctrl+X");
  _hotkey->insertItem("Ctrl+Y");
  _hotkey->insertItem("Ctrl+Z");
  _hotkey->insertItem("Ctrl+0");
  _hotkey->insertItem("Ctrl+1");
  _hotkey->insertItem("Ctrl+2");
  _hotkey->insertItem("Ctrl+3");
  _hotkey->insertItem("Ctrl+4");
  _hotkey->insertItem("Ctrl+5");
  _hotkey->insertItem("Ctrl+6");
  _hotkey->insertItem("Ctrl+7");
  _hotkey->insertItem("Ctrl+8");
  _hotkey->insertItem("Ctrl+9");

  _action->addColumn( tr("Action Name"),  200, Qt::AlignLeft );
  _action->addColumn( tr("Display Name"), -1,  Qt::AlignLeft );

  QStringList addedactions;
  QString dspname;
  XTreeWidgetItem *last = 0;
  for (ActionSet::iterator action = omfgThis->actions.begin(); action != omfgThis->actions.end(); action++)
  {
    if(!addedactions.contains((*action)->name()))
    {
      addedactions.append((*action)->name());
      last = new XTreeWidgetItem(_action, last, -1,
				 QVariant((*action)->name()),
				 QString((*action)->displayName()).remove("&")); 
    }
  }
  _action->sortItems(0,Qt::AscendingOrder);
}

/*
 *  Destroys the object and frees any allocated resources
 */
hotkey::~hotkey()
{
  // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void hotkey::languageChange()
{
  retranslateUi(this);
}

enum SetResponse hotkey::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
      _mode = cNew;
    else if (param.toString() == "edit")
    {
      _mode = cEdit;
      _hotkey->setEnabled(FALSE);
    }
  }

  param = pParams.value("username", &valid);
  if (valid)
  {
    _username = param.toString();
    _currentUser = FALSE;
  }

  param = pParams.value("currentUser", &valid);
  if (valid)
    _currentUser = TRUE;

  param = pParams.value("hotkey", &valid);
  if (valid)
  {
    QString value;

    if (_currentUser)
      value = _preferences->value(param.toString());
    else
    {
      q.prepare( "SELECT usrpref_value "
                 "FROM usrpref "
                 "WHERE ( (usrpref_username=:username)"
                 " AND (usrpref_name=:name) );" );
      q.bindValue(":username", _username);
      q.bindValue(":name", param.toString());
      q.exec();
      if (q.first())
        value = q.value("usrpref_value").toString();
//  ToDo
    }

    if (!value.isNull())
    {
      for (int i = 0; i < _action->topLevelItemCount(); i++)
      {
	XTreeWidgetItem *cursor = _action->topLevelItem(i);
        if (param.toString().left(1) == "F")
          _hotkey->setText(QString("F%1").arg(param.toString().right(1)));
        else if (param.toString().left(1) == "C")
          _hotkey->setText(QString("Ctrl+%1").arg(param.toString().right(1)));

        if (cursor->text(0) == value)
        {
          _action->setCurrentItem(cursor);
          _action->scrollToItem(cursor);
          break;
        }
      }
    }
  }

  return NoError;
}

void hotkey::sSave()
{
  QString keyValue;

  if(_action->currentItem() == 0)
  { 
    QMessageBox::information( this, tr("No Action Selected"),
      tr("You must select an Action before saving this Hotkey.") );
    return;
  }

  if (_hotkey->currentText().left(1) == tr("F"))
    keyValue = QString("F%1").arg(_hotkey->currentText().right(1));
  else if (_hotkey->currentText().left(5) == "Ctrl+")
    keyValue = QString("C%1").arg(_hotkey->currentText().right(1));

  if (_currentUser)
  {
    _preferences->set(keyValue, _action->currentItem()->text(0));
    _preferences->load();
  }
  else
  {
    q.prepare("SELECT setUserPreference(:username, :name, :value);");
    q.bindValue(":username", _username);
    q.bindValue(":name", keyValue);
    q.bindValue(":value", _action->currentItem()->text(0));
    q.exec();
  }

  accept();
}

