/***************************************************************************
 *   Copyright (C) 2008 by SK Communications.                              *
 *   http://kldp.net/projects/nateon/                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   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.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "messageboxwidget.h"
#include "sqlitedb.h"

messageboxWidget::messageboxWidget(QWidget* parent, const char* name, WFlags fl)
: messageboxWidgetBase(parent,name,fl),
pDB(0), pMemoSearch(0), pChatSearch(0)
{
  /*
  tab
  tab_2
  */
  pListViews = new ListViews(memoFrame, "ListViews" );
  Widget8Layout = new QVBoxLayout( memoFrame, 0, 0, "Widget8Layout");
  Widget8Layout->addWidget( pListViews );
  pListViews->createMemoTree();
  pListViews->createMemoMouseMenu();
  connect(pListViews->messages, SIGNAL( doubleClicked( QListViewItem *, const QPoint& , int ) ), SLOT( slotDoubleClick( QListViewItem *, const QPoint &, int ) ) );
  // connect(pListViews->messages, SIGNAL( showMemo( const QString & ) ), SLOT( slotMemoView( const QString & ) ) );
  pListViews->show();

  pListViews_2 = new ListViews(chatFrame, "ListViews_2" );
  Widget9Layout = new QVBoxLayout( chatFrame, 0, 0, "Widget9Layout");
  Widget9Layout->addWidget( pListViews_2 );
  pListViews_2->createChatTree();
  pListViews_2->createChatMouseMenu();
  pListViews_2->show();

  DCOPClient *client = kapp->dcopClient();
  client->attach();

  pDB = new SQLiteDB();

  pMemoSearch= new SearchForm(this);
  pChatSearch= new SearchForm(this);

  connect( pMemoSearch, SIGNAL( searchArg( int, const QString & ) ), this, SLOT( slotMemoSearch( int, const QString & ) ) );
  connect( pChatSearch, SIGNAL( searchArg( int, const QString & ) ), this, SLOT( slotChatSearch( int, const QString & ) ) );

  connect( pListViews->menu, SIGNAL( activated ( int ) ), this, SLOT( slotMouseRight( int ) ) );
  connect( pListViews_2->menu, SIGNAL( activated ( int ) ), this, SLOT( slotChatMouseRight( int ) ) );

  /*! 메모 툴바 */
  connect( memoWriteButton, SIGNAL( clicked() ), this, SLOT( slotMemoWrite() ) );
  connect( memoReplyButton, SIGNAL( clicked() ), this, SLOT( slotMemoReply() ) );
  connect( memoReplyAllButton, SIGNAL( clicked() ), this, SLOT( slotMemoReplyAll() ) );
  connect( memoForwardButton, SIGNAL( clicked() ), this, SLOT( slotMemoForward() ) );
  connect( memoSaveButton, SIGNAL( clicked() ), this, SLOT( slotMemoSave() ) );
  connect( memoDeleteButton, SIGNAL( clicked() ), this, SLOT( slotMemoDelete() ) );
  connect( memoFindButton, SIGNAL( clicked() ), this, SLOT( slotMemoFind() ) );
  connect( memoRefreshButton, SIGNAL( clicked() ), this, SLOT( slotMemoRefresh() ) );
  connect( memoHelpButton, SIGNAL( clicked() ), this, SLOT( slotMemoHelp() ) );

  /*! 대화 툴바 */
  connect( chatGoChatButton, SIGNAL( clicked() ), this, SLOT( slotGoChat() ) );
  connect( chatSaveButton, SIGNAL( clicked() ), this, SLOT( slotChatSave() ) );
  connect( chatDeleteButton, SIGNAL( clicked() ), this, SLOT( slotChatDelete() ) );
  connect( chatFindButton, SIGNAL( clicked() ), this, SLOT( slotChatFind() ) );
  connect( chatRefreshButton, SIGNAL( clicked() ), this, SLOT( slotChatRefresh() ) );
  connect( chatHelpButton, SIGNAL( clicked() ), this, SLOT( slotChatHelp() ) );

  connect(pListViews, SIGNAL( setUNREAD( QListViewItem* ) ), this, SLOT( slotSetUNREAD(  QListViewItem* ) ) );
  connect(pListViews, SIGNAL( setREAD( QListViewItem* ) ), this, SLOT( slotSetREAD(  QListViewItem* ) ) );
  connect(tabWidget2, SIGNAL( currentChanged ( QWidget* ) ), SLOT( slotChangeTab( QWidget* ) ) );
  connect(pListViews, SIGNAL( showMemoInbox() ), this, SLOT(slotShowMemoInbox() ) );
  connect(pListViews, SIGNAL( showMemoOutbox() ), this, SLOT(slotShowMemoOutbox() ) );
  connect(pListViews_2, SIGNAL( showChatBox() ), this, SLOT(slotShowChatBox() ) );

	connect(pListViews, SIGNAL( multiItemsSelected( bool ) ), SLOT( slotMultiItemsSelectedEnv( bool ) ) );
	connect(pListViews_2, SIGNAL( multiItemsSelected( bool ) ), SLOT( slotMultiItemsSelectedEnv( bool ) ) );

	// showMemoAllInbox();
}

messageboxWidget::~messageboxWidget()
{}

/*$SPECIALIZATION$*/
void messageboxWidget::button_clicked()
{
/*
  if ( label->text().isEmpty() )
  {
    label->setText( "Hello World!" );
  }
  else
  {
    label->clear();
  }
*/

}

void messageboxWidget::slotListing(const QString & sPath)
{
  /*! 전역변수에 저장 */
  sDBPath = sPath;
  sMemoInboxDBFilePath = sDBPath + "/memodata/local_inbox.db";
  sMemoOutboxDBFilePath = sDBPath + "/memodata/local_outbox.db";
  sChatBoxDBFilePath = sDBPath + "/chatdata/local_chat.db";
  sUserDBFilePath = sDBPath + "/local_user.db";
	// pListViews->initFolders();
	pListViews->clearList();
	showMemoAllInbox();
	pListViews->refresh();
	
  /*! 리스팅이 끝나고 명령을 knateon으로 부터 받는다. */
  dcopGetCommand();
}

void messageboxWidget::requireDBPath()
{
  // kdDebug() << "HHHHHHHHHHHHHEEEEEEEEEEEEEEERRRRRRRRRRRRRRRREEEEEEEEEEEEE" << endl;
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  stream << QString::fromUtf8("DB:PATH");
  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}

void messageboxWidget::slotSetUNREAD(QListViewItem * item)
{
  setUNREAD( item );
}

void messageboxWidget::setUNREAD(QListViewItem * item)
{
  QString sQuery;
  // QString sFilePath;

  int n = pListViews->getFolderIndex();
  if ( n == 0 )
  {
    sQuery = "UPDATE ";
    sQuery += "tb_local_inbox ";
    sQuery += "SET UNREAD=1 ";
    sQuery += "WHERE UUID='";
    sQuery += item->text(0);
    sQuery += "';";

    // sFilePath = sMemoInboxDBFilePath;
    pDB->execOne( sMemoInboxDBFilePath, sQuery );

    /*!
      knateon에 쪽지개수 갱신
    */
#ifdef NETDEBUG
    kdDebug() << "[ NEW MEMO COUNT ] : " << QString::number( getNewMemoCount() ) << endl;
#endif
    DCOPClient *client=kapp->dcopClient();
    QByteArray params;
    QDataStream stream(params, IO_WriteOnly);
    stream << QString::fromUtf8("MEMO:COUNT:" + QString::number( getNewMemoCount() ) );
    if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
      kdDebug() << "Error with DCOP\n" ;
  }
  else
  {
    sQuery = "UPDATE ";
    sQuery += "tb_local_outbox ";
    sQuery += "SET UNREAD=1 ";
    sQuery += "WHERE UUID='";
    sQuery += item->text(0);
    sQuery += "';";

    // sFilePath = sMemoInboxDBFilePath;
    pDB->execOne( sMemoOutboxDBFilePath, sQuery );
  }
  // kdDebug() << "FILEPATH : [" << sFilePath << "]" << endl;
}

void messageboxWidget::setREAD(QListViewItem * item)
{
  QString sQuery;

  int n = pListViews->getFolderIndex();
  if ( n == 0 )
  {
    sQuery = "UPDATE ";
    sQuery += "tb_local_inbox ";
    sQuery += "SET UNREAD=0 ";
    sQuery += "WHERE UUID='";
    sQuery += item->text(0);
    sQuery += "';";

    // sFilePath = sMemoInboxDBFilePath;
    pDB->execOne( sMemoInboxDBFilePath, sQuery );

    /*!
      knateon에 쪽지개수 갱신
    */
    DCOPClient *client=kapp->dcopClient();
    QByteArray params;
    QDataStream stream(params, IO_WriteOnly);
    stream << QString::fromUtf8("MEMO:COUNT:" + QString::number( getNewMemoCount() ) );
    if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
      kdDebug() << "Error with DCOP\n" ;
  }
  else
  {
    sQuery = "UPDATE ";
    sQuery += "tb_local_outbox ";
    sQuery += "SET UNREAD=0 ";
    sQuery += "WHERE UUID='";
    sQuery += item->text(0);
    sQuery += "';";

    // sFilePath = sMemoInboxDBFilePath;
    pDB->execOne( sMemoOutboxDBFilePath, sQuery );
  }
#if 0
  sQuery = "UPDATE ";
  sQuery += "tb_local_inbox ";
  sQuery += "SET UNREAD=0 ";
  sQuery += "WHERE UUID='";
  sQuery += item->text(0);
  sQuery += "';";

  QString sFilePath( sMemoInboxDBFilePath );
  // kdDebug() << "FILEPATH : [" << sFilePath << "]" << endl;

  pDB->execOne( sFilePath, sQuery );
#endif
}

void messageboxWidget::slotSetREAD(QListViewItem * item)
{
  setREAD( item );
}

QString messageboxWidget::getNameByID(QString sID)
{
  rowList mRow;
  QString sFilePath( sUserDBFilePath );
  QString sQuery("SELECT EMAIL from tb_user WHERE ID='");
  sQuery += sID;
  sQuery += "';";
  mRow = pDB->getRecords( sFilePath, sQuery );
  if ( mRow.isEmpty() )
    return sID;
  else
    return mRow.first()[0];
}

void messageboxWidget::slotChangeTab(QWidget * wg)
{
	pListViews->messages->clearSelection();
	pListViews_2->messages->clearSelection();
	
  if ( wg == tab )
  {
  	pListViews->initFolders();
	  emit changeShowTab( 0 );
  }
  if ( wg == tab_2 )
  {
    pListViews_2->initFolders();
	  emit changeShowTab( 1 );
  }
}

void messageboxWidget::showMemoAllInbox()
{
  showMemoInbox( "SELECT UUID, SUSER, RUSER, SUBJECT, BODYDATA, DATE, UNREAD, ISDELETED from tb_local_inbox;" );
}

void messageboxWidget::showMemoInbox( const QCString & sQuery )
{
  // QString sFilePath;
  rowList mRow;

  pListViews->clearList();

  /*! memo */
  // sFilePath = sDBPath + "/memodata/local_inbox.db";
  // kdDebug() << "[ F I L E P A T H ] [" << sFilePath << "]" << endl;
  mRow = pDB->getRecords( sMemoInboxDBFilePath, sQuery );

  for ( rowList::iterator it = mRow.begin(); it != mRow.end(); ++it )
  {
	  // kdDebug() << "[" << (*it)[0] << "] [" << (*it)[1] << "] [" << (*it)[2] << "] [" << (*it)[3] << "] [" << (*it)[4] << "] [" << (*it)[5] << "] [" << endl;

/*!
void ListViews::addMemoInbox(const QString & sID, const QString & sSender, const QString & sReceivers, const QString & sSubject, const QString & sBody, const QString & sDateTime)
*/
    /*! ISDELETED == 1 이면 */
    if ( (*it)[7] != "1" )
    {
      QString sTmp2;
      if ( (*it)[5].length() == 14 )
      {
        QString sTmp( (*it)[5] );
        QString sYear( sTmp.left(4) );
        QString sMonth( sTmp.mid(4,2) );
        QString sDay( sTmp.mid(6,2) );
        QString sHour( sTmp.mid(8,2) );
        QString sMinute( sTmp.mid(10,2) );
        QString sSecond( sTmp.mid(12,2) );
        sTmp2 = sYear;
        sTmp2 += "-";
        sTmp2 += sMonth;
        sTmp2 += "-";
        sTmp2 += sDay;
        sTmp2 += " ";
        sTmp2 += sHour;
        sTmp2 += ":";
        sTmp2 += sMinute;
        sTmp2 += ":";
        sTmp2 += sSecond;
      }
      else
      {
        QString sTmp2( (*it)[5] );
      }

      QStringList slList = QStringList::split( QString(";"), (*it)[1] );
      QString sSender;
      for ( QStringList::Iterator it2 = slList.begin(); it2 != slList.end(); ++it2 )
      {
        if (sSender.length() > 1)
          sSender += ";";
        sSender +=getNameByID( *it2 );
      }

      slList.clear();
      slList = QStringList::split( QString(";"), (*it)[2] );
      QString sReceivers;
      for ( QStringList::Iterator it2 = slList.begin(); it2 != slList.end(); ++it2 )
      {
        if (sReceivers.length() > 1)
          sReceivers += ";";
        sReceivers +=getNameByID( *it2 );
      }

      /*! 읽지 않았으면, UNREAD == '1' */
      if ( (*it)[6] == "1" )
        pListViews->addMemoInbox((*it)[0], sSender, sReceivers, (*it)[3], (*it)[4], sTmp2, false );
      else
        pListViews->addMemoInbox((*it)[0], sSender, sReceivers, (*it)[3], (*it)[4], sTmp2, true );
    }
  }
}

void messageboxWidget::showMemoAllOutbox()
{
  showMemoOutbox( "SELECT UUID, SUSER, RUSER, SUBJECT, BODYDATA, DATE, UNREAD, ISDELETED from tb_local_outbox;" );
}

void messageboxWidget::showMemoOutbox( const QCString & sQuery )
{
  // QString sFilePath;
  rowList mRow;

  pListViews->clearList();

  /*! memo */
  // sFilePath = sDBPath + "/memodata/local_outbox.db";
  // kdDebug() << "[ F I L E P A T H ] [" << sFilePath << "]" << endl;
  mRow = pDB->getRecords( sMemoOutboxDBFilePath, sQuery );

  for ( rowList::iterator it = mRow.begin(); it != mRow.end(); ++it )
  {
    // kdDebug() << "[" << (*it)[0] << "] [" << (*it)[1] << "] [" << (*it)[2] << "] [" << (*it)[3] << "] [" << (*it)[4] << "] [" << (*it)[5] << "] [" << endl;

/*!
void ListViews::addMemoInbox(const QString & sID, const QString & sSender, const QString & sReceivers, const QString & sSubject, const QString & sBody, const QString & sDateTime)
*/
    /*! ISDELETED == 1 이면 */
    if ( (*it)[7] != "1" )
    {
      QString sTmp2;
      if ( (*it)[5].length() == 14 )
      {
        QString sTmp( (*it)[5] );
        QString sYear( sTmp.left(4) );
        QString sMonth( sTmp.mid(4,2) );
        QString sDay( sTmp.mid(6,2) );
        QString sHour( sTmp.mid(8,2) );
        QString sMinute( sTmp.mid(10,2) );
        QString sSecond( sTmp.mid(12,2) );
        sTmp2 = sYear;
        sTmp2 += "-";
        sTmp2 += sMonth;
        sTmp2 += "-";
        sTmp2 += sDay;
        sTmp2 += " ";
        sTmp2 += sHour;
        sTmp2 += ":";
        sTmp2 += sMinute;
        sTmp2 += ":";
        sTmp2 += sSecond;
      }
      else
      {
        QString sTmp2( (*it)[5] );
      }

      QStringList slList = QStringList::split( QString(";"), (*it)[1] );
      QString sSender;
      for ( QStringList::Iterator it2 = slList.begin(); it2 != slList.end(); ++it2 )
      {
        if (sSender.length() > 1)
          sSender += ";";
        sSender +=getNameByID( *it2 );
      }

      slList.clear();
      slList = QStringList::split( QString(";"), (*it)[2] );
      QString sReceivers;
      for ( QStringList::Iterator it2 = slList.begin(); it2 != slList.end(); ++it2 )
      {
        if (sReceivers.length() > 1)
          sReceivers += ";";
        sReceivers +=getNameByID( *it2 );
      }

      /*! 읽지 않았으면, UNREAD == '1' */
      if ( (*it)[6] == "1" )
        pListViews->addMemoOutbox((*it)[0], sSender, sReceivers, (*it)[3], (*it)[4], sTmp2, false );
      else
        pListViews->addMemoOutbox((*it)[0], sSender, sReceivers, (*it)[3], (*it)[4], sTmp2, true );
    }
  }
}

void messageboxWidget::showChatAllList()
{
  showChatList( "SELECT UUID, CHATUSERS, BODYDATA, DATE, ISDELETED from tb_local_chat;" );
}

void messageboxWidget::showChatList( const QCString & sQuery )
{
  // QString sFilePath;
  pListViews_2->clearList();

  
  /*! chat */
  // sFilePath = sDBPath + "/chatdata/local_chat.db";
#ifdef NETDEBUG
  kdDebug() << "[ QUERY XXX ] [" << sQuery << "]" << endl;
#endif
  rowList mRow;
  mRow = pDB->getRecords( sChatBoxDBFilePath, sQuery );

  for ( rowList::iterator it = mRow.begin(); it != mRow.end(); ++it )
  {
    // kdDebug() << "[" << (*it)[0] << "] [" << (*it)[1] << "] [" << (*it)[2] << "] [" << (*it)[3] << "] [" << (*it)[4] << "]" << endl;
/*!
void ListViews::addMemoInbox(const QString & sID, const QString & sSender, const QString & sReceivers, const QString & sSubject, const QString & sBody, const QString & sDateTime)
*/
    /*! ISDELETED == 1 이면 */
    if ( (*it)[4] != "1" )
    {
      QString sTmp2;
      if ( (*it)[3].length() == 14 )
      {
        QString sTmp( (*it)[3] );
        QString sYear( sTmp.left(4) );
        QString sMonth( sTmp.mid(4,2) );
        QString sDay( sTmp.mid(6,2) );
        QString sHour( sTmp.mid(8,2) );
        QString sMinute( sTmp.mid(10,2) );
        QString sSecond( sTmp.mid(12,2) );
        sTmp2 = sYear;
        sTmp2 += "-";
        sTmp2 += sMonth;
        sTmp2 += "-";
        sTmp2 += sDay;
        sTmp2 += " ";
        sTmp2 += sHour;
        sTmp2 += ":";
        sTmp2 += sMinute;
        sTmp2 += ":";
        sTmp2 += sSecond;
      }
      else
      {
        QString sTmp2( (*it)[3] );
      }

      QStringList slList = QStringList::split( QString(";"), (*it)[1] );
      QString sSender;
      for ( QStringList::Iterator it2 = slList.begin(); it2 != slList.end(); ++it2 )
      {
        if (sSender.length() > 1)
          sSender += ";";
        sSender +=getNameByID( *it2 );
      }
      QString sSubject;
      slList.clear();
      slList = QStringList::split( QString("\n"), (*it)[2] );
      for ( QStringList::Iterator it2 = slList.begin(); it2 != slList.end(); ++it2 )
      {
        if ( (*it2).length() > 1 )
        {
          sSubject = *it2;
          break;
        }
      }

      pListViews_2->addChatBox((*it)[0], sSender, "", sSubject, (*it)[2], sTmp2, true );
    }
  }
}

/*!
  DCOP을 이용해서 knateon에
  새쪽지 보내기를 한다.
*/
void messageboxWidget::slotMemoWrite()
{
  // kdDebug() << "HHHHHHHHHHHHHEEEEEEEEEEEEEEERRRRRRRRRRRRRRRREEEEEEEEEEEEE" << endl;
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  stream << QString::fromUtf8("MEMO:NEW");
  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}
/*!
  DCOP을 이용해서 knateon에
  쪽지 답장을 보낸다.
*/
void messageboxWidget::slotMemoReply()
{
	QListViewItem *pListViewItem;
	pListViewItem = pListViews->getCurrentItem();

	if ( pListViewItem == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	QString sUUID( pListViewItem->text(0) );

  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);

  if ( pListViews->getFolderIndex() == 0 )
    stream << QString::fromUtf8( "MEMO:INBOX:REPLY:" + sUUID );
  else
    stream << QString::fromUtf8( "MEMO:OUTBOX:REPLY:" + sUUID );

  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}

void messageboxWidget::slotMemoReplyAll()
{
	QListViewItem *pListViewItem;
	pListViewItem = pListViews->getCurrentItem();
	
	if ( pListViewItem == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	QString sUUID( pListViewItem->text(0) );
	
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  // stream << QString::fromUtf8( "MEMO:REPLYALL:" + sUUID );
  if ( pListViews->getFolderIndex() == 0 )
    stream << QString::fromUtf8( "MEMO:INBOX:REPLYALL:" + sUUID );
  else
    stream << QString::fromUtf8( "MEMO:OUTBOX:REPLYALL:" + sUUID );

  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}

void messageboxWidget::slotMemoForward()
{
	QListViewItem *pListViewItem;
	pListViewItem = pListViews->getCurrentItem();
	
	if ( pListViewItem == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	QString sUUID( pListViewItem->text(0) );
	
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  // stream << QString::fromUtf8( "MEMO:FORWARD:" + sUUID );
  if ( pListViews->getFolderIndex() == 0 )
    stream << QString::fromUtf8( "MEMO:INBOX:FORWARD:" + sUUID );
  else
    stream << QString::fromUtf8( "MEMO:OUTBOX:FORWARD:" + sUUID );

  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}

void messageboxWidget::slotMemoSave()
{
	if (pListViews->getCurrentItem() == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}

	QString sData( pListViews->getText() );
  sData.replace( "<br>", "\n" );
  sData.replace( QRegExp("\\<[/a-z]*\\>"), "" );
  sData.replace( "&gt;", ">");
  sData.replace( "&lt;", "<");
  sData.replace( QRegExp("\\<a href=.*\\\"\\>"), "");

#if 1
  QString s = QFileDialog::getSaveFileName(
                    QDir::homeDirPath(),
                    "Text files (*.txt)",
                    this,
                    i18n("파일로 저장"),
                    i18n("저장할 파일명") );

  QFileInfo finfo( s );
  QString ext = finfo.extension();
  QString sf;
  if ( ext.length() > 0 )
    sf = s;
  else
  {
    sf = s;
    sf += ".txt";
  }
  QFile file( sf );
  if ( file.open( IO_WriteOnly ) ) {
    QTextStream stream( &file );
    /*
    for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
      stream << *it << "\n";
    */
    stream << sData << endl;
    file.close();
  }
#endif
#ifdef NETDEBUG
  kdDebug() << sData << endl;
#endif
}

/*!
  삭제
*/
void messageboxWidget::slotMemoDelete()
{
	if ( pListViews->getCurrentItem() == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	int result = KMessageBox::questionYesNo(this, QString::fromUtf8("선택한 쪽지를 삭제하시겠습니까?"), i18n("쪽지 삭제") );
  if ( result == KMessageBox::No ) return;

	bool bIsNotSelected = TRUE;
	QListViewItem * myChild = pListViews->messages->firstChild();
	while( myChild ) {
		if ( myChild->isSelected() )
		{
			QString sUUID( myChild->text(0) );
			QString sQuery;
			
			int n = pListViews->getFolderIndex();
			if ( n == 0 )
			{
				sQuery = "DELETE FROM tb_local_inbox WHERE UUID='";
				sQuery += sUUID;
				sQuery += "';";
				pDB->execOne( sMemoInboxDBFilePath, sQuery );
			}
			else
			{
				sQuery = "DELETE FROM tb_local_outbox WHERE UUID='";
				sQuery += sUUID;
				sQuery += "';";
				pDB->execOne( sMemoOutboxDBFilePath, sQuery );
			}
			// pListViews->removeItem( myChild );
			bIsNotSelected = FALSE;
		}
		myChild = myChild->nextSibling();
	}

	if ( bIsNotSelected )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
	}
	else
	{
		slotMemoRefresh();
	}
	
#if 0
  /*!삭제 Query */
	QListViewItem *pListViewItem;
	pListViewItem = pListViews->getCurrentItem();
	
	if ( pListViewItem == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	QString sUUID( pListViewItem->text(0) );
	QString sQuery;
  // kdDebug() << sUUID << endl;

  int n = pListViews->getFolderIndex();
  if ( n == 0 )
  {
    sQuery = "DELETE FROM tb_local_inbox WHERE UUID='";
    sQuery += sUUID;
    sQuery += "';";
    pDB->execOne( sMemoInboxDBFilePath, sQuery );
  }
  else
  {
    sQuery = "DELETE FROM tb_local_outbox WHERE UUID='";
    sQuery += sUUID;
    sQuery += "';";
    pDB->execOne( sMemoOutboxDBFilePath, sQuery );
  }

  /*!
    ListView에서 현재 항목을 삭제한다.
  */
  pListViews->removeCurrentItem();
#endif
}

void messageboxWidget::slotMemoFind()
{
  // pSearchDialog = new SearchForm(this, "searchdialog", FALSE, 0);
  pMemoSearch->init();
  // int n = pListViews->getFolderIndex();
  // pListViews->clearList();
  pMemoSearch->searchComboBox->insertItem( i18n("제목") );
  pMemoSearch->searchComboBox->insertItem( i18n("보낸 사람") );
  pMemoSearch->searchComboBox->insertItem( i18n("받은 사람") );
  /*
  if ( n == 0 )
  {
    showMemoAllInbox();
  }
  else
  {
    showMemoAllOutbox();
  }
  */
  pMemoSearch->show();
}

void messageboxWidget::slotMemoRefresh()
{
  int n = pListViews->getFolderIndex();
  pListViews->clearList();
  if ( n == 0 )
  {
    showMemoAllInbox();
  }
  else
  {
    showMemoAllOutbox();
  }
  pListViews->refresh();
}

void messageboxWidget::slotMemoHelp()
{
	LNMUtils::openURL("http://nateonweb.nate.com/help/maclinux/linux_g_08.htm" );
}

void messageboxWidget::slotGoChat()
{
	QListViewItem *pListViewItem;
	pListViewItem = pListViews_2->getCurrentItem();
	
	if ( pListViewItem == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	QString sUUID( pListViewItem->text(0) );
	
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  stream << QString::fromUtf8( "CHAT:" + sUUID );
  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}

void messageboxWidget::slotChatSave()
{
  QListViewItem *pListViewItem;
  pListViewItem = pListViews_2->getCurrentItem();
  
  if ( pListViewItem == 0 )
  {
    KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
    return;
  }
  
  QString sData( pListViews_2->getText() );
  sData.replace( "<br>", "\n" );
  sData.replace( QRegExp("\\<[/a-z]*\\>"), "" );
  sData.replace( "&gt;", ">");
  sData.replace( "&lt;", "<");
  sData.replace( QRegExp("\\<a href=.*\\\"\\>"), "");
#ifdef NETDEBUG
  kdDebug() << sData << endl;
#endif
  
  QString sSaveFile = QFileDialog::getSaveFileName(
                    QDir::homeDirPath(),
                    "Text files (*.txt)",
                    this,
                    i18n("파일로 저장"),
                    i18n("저장할 파일명") );
  
  if (!sSaveFile.isEmpty())
  {
		QFile file( sSaveFile );
		if ( file.open( IO_WriteOnly ) )
		{
			QTextStream stream( &file );
			/*
			for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
				stream << *it << "\n";
			*/
			stream << sData << endl;
			file.close();
  		KMessageBox::information( this, i18n("대화가 \"") + sSaveFile + i18n("\" 파일로 저장되었습니다."), i18n("대화 저장") );
		}
  }
#if 0
  else
  {
    KMessageBox::information( this, i18n("저장할 파일 선택을 하셔야 됩니다."), i18n("대화 저장") );
  }
#endif
}

void messageboxWidget::slotChatDelete()
{
	if ( pListViews_2->getCurrentItem() == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}

	int result = KMessageBox::questionYesNo(this, QString::fromUtf8("선택한 대화를 삭제하시겠습니까?"), i18n("대화 삭제") );
	if ( result == KMessageBox::No ) return;
	
	bool bIsNotSelected = TRUE;
	QListViewItem * myChild = pListViews_2->messages->firstChild();
	while( myChild ) {
		if ( myChild->isSelected() )
		{
			QString sUUID( myChild->text(0) );
			QString sQuery;
			sQuery = "DELETE FROM tb_local_chat WHERE UUID='";
			sQuery += sUUID;
			sQuery += "';";
			pDB->execOne( sChatBoxDBFilePath, sQuery );
			bIsNotSelected = FALSE;
		}
		myChild = myChild->nextSibling();
	}
	
	if ( bIsNotSelected )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
	}
	else
	{
		slotChatRefresh();
	}
	
#if 0
	QListViewItem *pListViewItem;
	pListViewItem = pListViews_2->getCurrentItem();
	
	if ( pListViewItem == 0 )
	{
		KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
		return;
	}
	
	QString sUUID( pListViewItem->text(0) );
	
  QString sQuery;
  sQuery = "DELETE FROM tb_local_chat WHERE UUID='";
  sQuery += sUUID;
  sQuery += "';";

  pDB->execOne( sChatBoxDBFilePath, sQuery );

  /*!
    ListView에서 현재 항목을 삭제한다.
  */
  pListViews_2->removeCurrentItem();
#endif
}

void messageboxWidget::slotChatFind()
{
  pChatSearch->init();
  pChatSearch->searchComboBox->insertItem( i18n("본문") );
  pChatSearch->searchComboBox->insertItem( i18n("대화 상대") );
  pChatSearch->show();
#if 0
  bool ok;
  QString text = QInputDialog::getText(
            i18n("대화상대/본문"), i18n("검색어 :"), QLineEdit::Normal,
            QString::null, &ok, this );
  if ( ok && !text.isEmpty() ) {}
#endif
}

void messageboxWidget::slotChatRefresh()
{
  // int n = pListViews_2->getFolderIndex();
  pListViews_2->clearList();
  showChatAllList();
  pListViews_2->refresh();
}

void messageboxWidget::slotChatHelp()
{
	LNMUtils::openURL("http://nateonweb.nate.com/help/maclinux/linux_g_08.htm" );
}

void messageboxWidget::slotShowMemoInbox()
{
  memoReplyButton->setEnabled();
  showMemoAllInbox();
	pListViews->messages->clearSelection();
	pListViews_2->messages->clearSelection();
}

void messageboxWidget::slotShowMemoOutbox()
{
  memoReplyButton->setDisabled();
  showMemoAllOutbox();
	pListViews->messages->clearSelection();
	pListViews_2->messages->clearSelection();
}

void messageboxWidget::slotShowChatBox()
{
  memoReplyButton->setEnabled();
  showChatAllList();
	pListViews->messages->clearSelection();
	pListViews_2->messages->clearSelection();
}

void messageboxWidget::slotMemoSearch(int nIdx, const QString & sKey)
{

  int n = pListViews->getFolderIndex();
  pListViews->clearList();
  if ( n == 0 )
  {
    QCString sQuery( "SELECT UUID, SUSER, RUSER, SUBJECT, BODYDATA, DATE, UNREAD, ISDELETED from tb_local_inbox" );
    if ( nIdx == 0 )
    {
      sQuery += " WHERE SUBJECT like \"%";
	    sQuery += sKey.utf8();
	    sQuery += "%\";";
	    // kdDebug() << "SQL : [" << sQuery << "]" << endl;
	    showMemoInbox( sQuery );
	    pListViews->refresh();
    }
    else if ( nIdx == 1 )
    {
	    slotMemoRefresh();
	    QListViewItem * myChild = pListViews->messages->firstChild();
	    QListViewItem * myNext = pListViews->messages->firstChild();
	    while( myNext ) {
		    myChild = myNext;
		    myNext = myChild->nextSibling();
		    if ( myChild->text(1).find( sKey ) == -1 ) {
			    pListViews->messages->removeItem( myChild );
		    }
	    }
	    /*
      sQuery += " WHERE SUSER like \"%";
	    sQuery += sKey.utf8();
	    sQuery += "%\";";
	    kdDebug() << "SQL : [" << sQuery << "]" << endl;
	    showMemoInbox( sQuery );
	    */
    }
    else
    {
      sQuery += " WHERE RUSER like \"%";
	    sQuery += sKey.utf8();
	    sQuery += "%\";";
	    // kdDebug() << "SQL : [" << sQuery << "]" << endl;
	    showMemoInbox( sQuery );
	    pListViews->refresh();
    }
  }
  else
  {
    QCString sQuery( "SELECT UUID, SUSER, RUSER, SUBJECT, BODYDATA, DATE, UNREAD, ISDELETED from tb_local_outbox" );
    if ( nIdx == 0 )
    {
      sQuery += " WHERE SUBJECT like \"%";
      sQuery += sKey.utf8();
	    sQuery += "%\";";
	    // kdDebug() << "SQL : [" << sQuery << "]" << endl;
	    showMemoOutbox( sQuery );
	    pListViews->refresh();
    }
    else if ( nIdx == 1 )
    {
	    slotMemoRefresh();
	    QListViewItem * myChild = pListViews->messages->firstChild();
	    QListViewItem * myNext = pListViews->messages->firstChild();
	    while( myNext ) {
		    myChild = myNext;
		    myNext = myChild->nextSibling();
		    if ( myChild->text(1).find( sKey ) == -1 ) {
			    pListViews->messages->removeItem( myChild );
		    }
	    }
	    /*
	    sQuery += " WHERE SUSER like \"%";
	    sQuery += sKey.utf8();
      sQuery += "%\";";
			*/
    }
    else
    {
      sQuery += " WHERE RUSER like \"%";
	    sQuery += sKey.utf8();
	    sQuery += "%\";";
	    // kdDebug() << "SQL : [" << sQuery << "]" << endl;
	    showMemoOutbox( sQuery );
	    pListViews->refresh();
    }
  }
}

void messageboxWidget::slotChatSearch(int nIdx, const QString & sKey)
{
  QCString sQuery;
  // pListViews_2->clearList();
	sQuery = "SELECT UUID, CHATUSERS, BODYDATA, DATE, ISDELETED from tb_local_chat";
	
	if ( nIdx == 0 )
  {
	  sQuery += " WHERE BODYDATA like '%";
	  sQuery += sKey.utf8();
	  sQuery += "%';";
	  showChatList( sQuery );
#ifdef NETDEBUG
	  kdDebug() << "[ Q U E R Y ] [" << sQuery << "]" << endl;
#endif
	  pListViews_2->refresh();
  }
  else
  {
	  slotChatRefresh();
	  QListViewItem * myChild = pListViews_2->messages->firstChild();
	  QListViewItem * myNext = pListViews_2->messages->firstChild();
	  while( myNext ) {
		  // doSomething( myChild );
		  myChild = myNext;
		  myNext = myChild->nextSibling();
		  if ( myChild->text(1).find( sKey ) == -1 ) {
			  pListViews_2->messages->removeItem( myChild );
		  }
	  }
  }
}

void messageboxWidget::slotMouseRight(int nId)
{
#ifdef NETDEBUG
  kdDebug() << "[ I D ] : [" << QString::number( nId ) << "]" << endl;
#endif

	/* int n = */ pListViews->getFolderIndex();

#if 0
  menu->insertItem( i18n( "읽지않은 상태로 변경(&B)" ), this, SLOT( slotUNREAD() ), 0, 0, 0 );
  menu->insertItem( i18n( "저장(&S)" ), this, SLOT( slotSave() ), CTRL+Key_S, 1, 1 );
  menu->insertItem( i18n( "답장(&R)" ), this, SLOT( slotReply() ), CTRL+Key_R, 2, 2 );
  menu->insertItem( i18n( "전체 답장(&A)" ), this, SLOT(slotReplyAll()), CTRL+SHIFT+Key_R, 3, 3 );
  menu->insertItem( i18n( "전달(&F)" ), this, SLOT(slotForward()), CTRL+SHIFT+Key_F, 4, 4 );
  menu->insertItem( i18n( "삭제(&D)" ), this, SLOT(slotDelete()), Key_Delete, 5, 5 );
#endif
  switch( nId )
  {
  case 1:
    // showMemo( messages->currentItem()->text(0) );
    slotMemoView( pListViews->messages->currentItem()->text(0) );
    break;
  case 2:
    slotMemoSave();
    break;
  case 3:
    slotMemoReply();
    break;
  case 4:
    slotMemoReplyAll();
    break;
  case 5:
    slotMemoForward();
    break;
  case 6:
    slotMemoDelete();
    break;
  }
}

void messageboxWidget::slotChatMouseRight(int nId)
{
#ifdef NETDEBUG
  kdDebug() << "[ I D ] : [" << QString::number( nId ) << "]" << endl;
#endif
#if 0
  menu->insertItem( i18n( "저장(&S)" ), this, SLOT( slotChatSave() ), CTRL+Key_S, 0, 0 );
  menu->insertItem( i18n( "삭제(&D)" ), this, SLOT(slotChatDelete()), Key_Delete, 0, 0 );
#endif
  switch( nId )
  {
    case 0:
      slotChatSave();
      break;
    case 1:
      slotChatDelete();
      break;
  }
}

int messageboxWidget::getNewMemoCount()
{
  rowList myList;
  myList = pDB->getRecords( sMemoInboxDBFilePath, "SELECT COUNT(*) FROM tb_local_inbox WHERE UNREAD=1;" );

  if ( myList.isEmpty() )
    return 0;
#ifdef NETDEBUG
  for ( rowList::iterator it = myList.begin(); it != myList.end(); ++it )
  {
    kdDebug() << "[ R E S U L T ] : "<< (*it) << endl;
  }
#endif
  return myList.first()[0].toInt();
}

void messageboxWidget::dcopGetCommand()
{
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  stream << QString::fromUtf8("CMD:GET");
  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}

void messageboxWidget::slotDoubleClick( QListViewItem * pItem, const QPoint & mPoint, int nID )
{
#ifdef NETDEBUG
  kdDebug() << "UUID : [" << pItem->text(0) << "]" << endl;
#endif
  // emit doubleClicked( pItem->text(0) );
  // QString sUUID( pListViews->getCurrentItem()->text(0) );
  
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  // stream << QString::fromUtf8( "MEMO:REPLYALL:" + sUUID );
  if ( pListViews->getFolderIndex() == 0 )
    stream << QString::fromUtf8( "MEMO:INBOX:VIEW:" + pItem->text(0) );
  
#if 0
  else
    stream << QString::fromUtf8( "MEMO:OUTBOX:VIEW:" + pItem->text(0) );
#endif
  
  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
	
	Q_UNUSED( mPoint );
	Q_UNUSED( nID );
}

void messageboxWidget::slotMemoView( const QString &sUUID )
{
  DCOPClient *client=kapp->dcopClient();
  QByteArray params;
  QDataStream stream(params, IO_WriteOnly);
  // stream << QString::fromUtf8( "MEMO:REPLYALL:" + sUUID );
  if ( pListViews->getFolderIndex() == 0 )
    stream << QString::fromUtf8( "MEMO:INBOX:VIEW:" + sUUID );
  
#if 0
  else
    stream << QString::fromUtf8( "MEMO:OUTBOX:VIEW:" + pItem->text(0) );
#endif
  
  if (!client->send("KNateOn-*", "knateondcop", "dcopCommand(QString)", params))
    kdDebug() << "Error with DCOP\n" ;
}


#include "messageboxwidget.moc"



void messageboxWidget::slotMultiItemsSelectedEnv(bool bMultiSelected)
{
	if ( bMultiSelected )
	{
		memoReplyButton->setDisabled();
		memoReplyAllButton->setDisabled();
		memoForwardButton->setDisabled();
		memoSaveButton->setDisabled();
		chatGoChatButton->setDisabled();
		chatSaveButton->setDisabled();
	}
	else
	{
		memoReplyButton->setEnabled();
		memoReplyAllButton->setEnabled();
		memoForwardButton->setEnabled();
		memoSaveButton->setEnabled();
		chatGoChatButton->setEnabled();
		chatSaveButton->setEnabled();
	}
}
