/***************************************************************************
 *   Copyright (C) 2007 by Anistratov Oleg                                 *
 *   ower@users.sourceforge.net                                            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2        *
 *   as published by the Free Software Foundation;                         *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 ***************************************************************************/

#include "inputtextwgt.h"

#include <QFile>
#include <QByteArray>
#include <QTextCursor>
#include <QTextFrame>

#include <stdlib.h>
#include <assert.h>

#include "qchatsettings.h"

static QString Chars_US("");
static QString Chars_UA("");
static QString Chars_RU("");
static bool inited = false;

InputTextWgt::InputTextWgt(QWidget *parent)
 : QTextEdit(parent),
  m_currentMsg      (""),
  m_msgHistory      (NULL),
  m_msgsSize        (0),
  m_currentMsgNumber(1),
  m_current         (0)
{
}
//\*****************************************************************************
void InputTextWgt::initChars(const QString & filename)
{
  QByteArray ba;
  QFile file(filename);

  if(!::inited && file.open(QIODevice::ReadOnly))
  {
    ba         = file.readLine();
    ::Chars_US = QString::fromUtf8(ba.data(), ba.size());
    ba         = file.readLine();
    ::Chars_RU = QString::fromUtf8(ba.data(), ba.size());
    ba         = file.readLine();
    ::Chars_UA = QString::fromUtf8(ba.data(), ba.size());
  }
  ::inited = true;
}
//\*****************************************************************************
void InputTextWgt::changeTextCharMap() // TODO rewrite
{
  QString str    = toPlainText();
  QTextCursor tc = textCursor();
  int i;
  QString original;
  QString replace;

  switch(m_current)
  {
    case 0 :
      original  = ::Chars_US;
      if(!::Chars_UA.isEmpty()){
        replace   = ::Chars_UA;
        m_current = 1;
      }
      else if(!::Chars_RU.isEmpty()){
        replace   = ::Chars_RU;
        m_current = 2;
      }
      else
        m_current = -1;
      break;

    case 1 :
      original  = ::Chars_UA;
      if(!::Chars_RU.isEmpty()){
        replace   = ::Chars_RU;
        m_current = 2;
      }
      else if(!::Chars_US.isEmpty()){
        replace   = ::Chars_US;
        m_current = 0;
      }
      else
        m_current = -1;
      break;

    case 2 :
      original  = ::Chars_RU;
      if(!::Chars_US.isEmpty()){
        replace   = ::Chars_US;
        m_current = 0;
      }
      else if(!::Chars_UA.isEmpty()){
        replace   = ::Chars_UA;
        m_current = 1;
      }
      else
        m_current = -1;
      break;
  }

  if(m_current < 0)
    return;

  for(i = 0; i < str.size(); i++)
    if(original.contains(str[i]))
      str[i] = replace[original.indexOf(str[i])];

  setPlainText(str);
  setTextCursor(tc);
}
//\*****************************************************************************
void InputTextWgt::keyPressEvent(QKeyEvent* ev)
{
  QKeySequence seq = ev->key() + ev->modifiers();

  if(QChatSettings::settings()->shortcuts("SendMessage").contains(seq))
    sendMsg();
  // FIXME shortcuts("SendMessage") can contain QKeySequence("Ctrl+Return") also
  else if(QChatSettings::settings()->shortcuts("SendMessage").contains(QKeySequence("Return")) &&
          QKeySequence("Ctrl+Return") == seq)
    insertPlainText("\n");

  else if(QChatSettings::settings()->shortcuts("ChangeTextCharMap").contains(seq))
    changeTextCharMap();

  else if(QChatSettings::settings()->shortcuts("NextMessage").contains(seq))
    nextMsg();

  else if(QChatSettings::settings()->shortcuts("PrevMessage").contains(seq))
    prevMsg();

  else if((ev->key()  == Qt::Key_Tab))
    QWidget::keyPressEvent(ev);

  else
    QTextEdit::keyPressEvent(ev);

}
//\*****************************************************************************
void InputTextWgt::nextMsg()
{
  if(m_currentMsgNumber + 1 >= 0 && m_currentMsgNumber + 1 < m_msgsSize)
  {
    m_currentMsgNumber++;
    setHtml(*m_msgHistory[m_currentMsgNumber]);
  }
  else if(m_currentMsgNumber + 1 == m_msgsSize)
  {
    m_currentMsgNumber++;
    setHtml(m_currentMsg);
  }
}
//\*****************************************************************************
void InputTextWgt::prevMsg   ()
{
  if(m_currentMsgNumber == m_msgsSize)
    m_currentMsg = toHtml();

  if(m_currentMsgNumber - 1 >= 0 && m_currentMsgNumber - 1 < m_msgsSize)
  {
    m_currentMsgNumber--;
    setHtml(*m_msgHistory[m_currentMsgNumber]);
  }
}
//\*****************************************************************************
void InputTextWgt::addMsg(const QString & msg)
{
  quint16 i;
  if(msg.isEmpty())
    return;

  if(m_msgHistory != NULL)
    for(i = 0; i < m_msgsSize; i++)
      if(*m_msgHistory[i] == msg)
      {
        *m_msgHistory[i]              = *m_msgHistory[m_msgsSize - 1];
        *m_msgHistory[m_msgsSize - 1] = msg;
        return;
      }

  ++m_msgsSize;

  m_msgHistory = (QString**)realloc(m_msgHistory, m_msgsSize * sizeof(QString*));
  assert(NULL != m_msgHistory);

  m_msgHistory[m_msgsSize - 1] = new QString(msg);
}
//\*****************************************************************************
void InputTextWgt::sendMsg()
{
//   addMsg(toPlainText());
  addMsg(toHtml());
  m_currentMsgNumber = m_msgsSize;
  emit wantSend();
}
