/***************************************************************************
 *   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 "messagebox.h"
#include "../nateon/util/common.h"

nmconfig stConfig;

messagebox::messagebox() 
:DCOPObject ( "messageviewer" ),
KMainWindow( 0, "messagebox" ),
pFile(0),
pMessage(0),
pTool(0),
pView(0),
pHelp(0)
{
  KStandardDirs   *dirs   = KGlobal::dirs();
	QString         sPicsPath( dirs->findResource( "data", QString( KGlobal::instance()->aboutData()->appName() ) + "/pics/" ) );

  setIcon( QPixmap( sPicsPath + "title_icon_tmb.bmp" ) );
  pMessageboxWidget = new messageboxWidget( this );
	connect( pMessageboxWidget, SIGNAL( changeShowTab( int ) ), SLOT( slotChangeTab( int ) ) );
  setCentralWidget( pMessageboxWidget );
  createMenu();

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

  connect( this, SIGNAL( gotDBPath( const QString & ) ), pMessageboxWidget, SLOT( slotListing( const QString & ) ) );
	// connect( )
  

  pMessageboxWidget->requireDBPath();
  // pMessageboxWidget->tabWidget2->setCurrentPage ( 1 );
}

/*
messagebox::~messagebox()
{
}
*/
void messagebox::createMenu()
{
  pFile = new KPopupMenu(this);
  menuBar()->insertItem( i18n("파일(&F)"), pFile);
	// pOpenAction = new KAction(i18n("열기(&O)"), 0, KShortcut( Qt::Key_Enter | Qt::CTRL + Qt::Key_X), this, SLOT( slotOpenMenu() ), this, "SendFile");
	pOpenAction = new KAction( this );
	pOpenAction->setText ( i18n("열기(&O)") );
	KShortcut openShortcut = pOpenAction->shortcut();
	// openShortcut.append( KKey(Key_Enter) );
	openShortcut.append( KKey( Qt::CTRL + Qt::Key_O ) );
	pOpenAction->setShortcut( openShortcut );
	connect( pOpenAction, SIGNAL( activated () ), SLOT( slotOpenMenu() ) );
	pOpenAction->plug( pFile );
	pSaveAction = new KAction(i18n("저장(&S)"), 0, KShortcut( Qt::CTRL + Qt::Key_S ), this, SLOT( slotSaveMenu() ), this, "SaveMenu");
	pSaveAction->plug( pFile );
	pFile->insertSeparator();
  pQuitAction = new KAction(i18n("메시지함 닫기(&X)"), 0, KShortcut( Qt::CTRL + Qt::Key_X ), this, SLOT( slotQuit() ), this, "SendFile");
  pQuitAction->plug( pFile );

  pMessage = new KPopupMenu(this);
  menuBar()->insertItem( i18n("메시지(&M)"), pMessage);
	pNewAction = new KAction(i18n("새 메시지(&M)"), 0, KShortcut( Qt::CTRL + Qt::Key_N ), this, SLOT( slotNewMenu() ), this, "NewMenu");
	pNewAction->plug( pMessage );
	pReplyMemoAction = new KAction(i18n("답장(&R)"), 0, KShortcut( Qt::CTRL + Qt::Key_R ), pMessageboxWidget, SLOT( slotMemoReply() ), this, "NewMenu");
	pReplyMemoAction->plug( pMessage );
	pReplyAllMemoAction = new KAction(i18n("전체 답장(&A)"), 0, KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_R ), pMessageboxWidget, SLOT( slotMemoReplyAll() ), this, "menu_reply");
	pReplyAllMemoAction->plug( pMessage );
	pForwardMemoAction = new KAction(i18n("전달(&F)"), 0, KShortcut( Qt::CTRL + Qt::Key_F ), pMessageboxWidget, SLOT( slotMemoForward() ), this, "menu_forword");
	pForwardMemoAction->plug( pMessage );
	pMessage->insertSeparator();
	// pDeleteAction = new KAction(i18n("삭제(&D)"), 0, KShortcut( Qt::Key_Delete ), pMessageboxWidget, SLOT( slotMemoDelete() ), this);
	pDeleteAction = new KAction(i18n("삭제(&D)"), 0, KShortcut( Qt::Key_Delete ), this, SLOT( slotDelete() ), this, "menu_delete");
	pDeleteAction->plug( pMessage );
	
  pTool = new KPopupMenu(this);
  menuBar()->insertItem( i18n("도구(&T)"), pTool);
	// pAlwaysTopAction = new KAction(i18n("항상 위(&Y)"), 0, KShortcut( Qt::CTRL + Qt::Key_Y ), this, SLOT( slotAlwaysTop() ), this);
	// KToggleAction(i18n("항상 위(&N)"), 0, 0, this, "alwaysTop");
	pAlwaysTopAction = new KToggleAction(i18n("항상 위(&Y)"), 0, KShortcut( Qt::CTRL + Qt::Key_Y ), this, "alwaysTop");
	connect( pAlwaysTopAction, SIGNAL( toggled( bool ) ), SLOT( slotAlwaysTop( bool ) ) );
	
	pAlwaysTopAction->plug( pTool );
	pTool->insertSeparator();
	pFindAction = new KAction(i18n("찾기(&F)"), 0, KShortcut( Qt::CTRL + Qt::Key_F ), this, SLOT( slotFindMenu() ), this, "menu_find" );
	pFindAction->plug( pTool );
	pSeletAllAction = new KAction(i18n("전체선택(&A)"), 0, KShortcut( Qt::CTRL + Qt::Key_A ), this, SLOT( slotSelectAll() ), this, "menu_selectall" );
	pSeletAllAction->plug( pTool );
	pTool->insertSeparator();
	pSetupAction = new KAction(i18n("통합메시지함 옵션"), 0, KShortcut( Qt::Key_F12 ), this, SLOT( slotSetup() ), this, "menu_option" );
	pSetupAction->setEnabled( FALSE );
	pSetupAction->plug( pTool );
	
  pView= new KPopupMenu(this);
  menuBar()->insertItem( i18n("보기(&V)"), pView);
	pRefreshAction = new KAction(i18n("새로 고침(&R)"), 0, KShortcut( Qt::Key_F5 ), this, SLOT( slotRefreshMenu() ), this, "menu_refresh" );
	pRefreshAction->plug( pView );
	
  pHelp = new KPopupMenu(this);
  menuBar()->insertItem( i18n("도움말(&V)"), pHelp);
	pNateDotComAction = new KAction(i18n("NATE.com 홈(&N)"), 0, KShortcut( Qt::Key_F11 ), this, SLOT( slotGoNateDotComMenu() ), this, "menu_natecom" );
	pNateDotComAction->plug( pHelp );
	pHelpAction = new KAction(i18n("통합메시지함 이용안내(&I)"), 0, KShortcut( Qt::Key_F1 ), this, SLOT( slotGoHelpMenu() ), this, "menu_usage" );
	pHelpAction->plug( pHelp );
	pHotTipAction = new KAction(i18n("네이트온 HotTip(&H)"), 0, 0, this, SLOT( slotGoHotTipMenu() ), this, "menu_hottip" );
	pNateDotComAction->plug( pHelp );
	pFaqAction = new KAction(i18n("네이트온 FAQ(&F)"), 0, 0, this, SLOT( slotGoFaqMenu() ), this, "menu_faq" );
	pFaqAction->plug( pHelp );
#if 0
	helpMenu_ = new KHelpMenu(this, KGlobal::instance()->aboutData(), false, actionCollection());
	pGonateoninfo = KStdAction::aboutApp(helpMenu_, SLOT( aboutApplication() ), actionCollection() );
#endif
	helpMenu_ = new KHelpMenu(this, KGlobal::instance()->aboutData(), false, actionCollection());
	// pAboutAction = new KAction(i18n("통합메시지함 정보(&V)"), 0, 0, this, SLOT( slotGoAboutMenu() ), this);
	pAboutAction = KStdAction::aboutApp(helpMenu_, SLOT( aboutApplication() ), actionCollection() );
	pAboutAction->plug( pHelp );
}

void messagebox::setUserID(const QString s)
{
#ifdef NETDEBUG
  kdDebug() << "YYY Receive Data : [" << s << "]" << endl;
#endif
  sUserID = s;
}

void messagebox::setDBPath(const QString s)
{
#ifdef NETDEBUG
  kdDebug() << "XXX Receive Data : [" << s << "]" << endl;
#endif
  sDBPath = s;

  emit gotDBPath( s );
  // openDB( s );
}


void messagebox::openDB( const QString& sPath )
{
#if 0
  QString sFilePath;
  rowList mRow;

  /*! memo */
  sFilePath = sPath;
  sFilePath += "/memodata/local_inbox.db";
  kdDebug() << "[ F I L E P A T H ] [" << sFilePath << "]" << endl;
  mRow = pDB->getRecords( sFilePath, "SELECT UUID, SUSER, RUSER, SUBJECT, BODYDATA, DATE from tb_local_inbox;");

  for ( rowList::iterator it = mRow.begin(); it != mRow.end(); ++it )
  {
    kdDebug() << "[" << (*it)[0] << "] [" << (*it)[1] << "] [" << (*it)[2] << "] [" << (*it)[3] << "] [" << (*it)[4] << "] [" << (*it)[5] << "] [" << endl;
  }
#if 0
  sFilePath = sPath;
  sFilePath += "/memodata/local_outbox.db";
  mRow = pDB->getRecords( sFilePath, "SELECT UUID, SUSER, RUSER, SUBJECT, BODYDATA, DATE from TB_local_outbox;");

  /*! chat */
  sFilePath = sPath;
  sFilePath += "/chatdata/local_chat.db";
  mRow = pDB->getRecords( sFilePath, "SELECT UUID, CHATUSER, BODYDATA, DATE, SIZE from tb_local_chat;");
#endif
#endif
	Q_UNUSED( sPath );
}

void messagebox::slotQuit()
{
  close();
}

void messagebox::dcopCommand(const QString s)
{
#ifdef NETDEBUG
  kdDebug() << "dcopCommand XXX [" << s << "]" << endl;
#endif
  QStringList slCommand = QStringList::split(QString(":"), s);
  if ( slCommand[0] == "VIEW" )
  {
    if ( slCommand[1] == "CHAT" )
    {
      pMessageboxWidget->tabWidget2->setCurrentPage ( 1 );
      pMessageboxWidget->pListViews_2->initFolders();
    }
    else if ( slCommand[1] == "MEMO" )
    {
      pMessageboxWidget->tabWidget2->setCurrentPage ( 0 );
	    pMessageboxWidget->pListViews->initFolders();
    }
  }
  else if ( slCommand[0] == "SEARCH" )
  {
    if ( slCommand[1] == "CHAT" )
    {
      // pMessageboxWidget->pListViews_2->initFolders();
      pMessageboxWidget->tabWidget2->setCurrentPage ( 1 );
      /*! 검색어 : slCommand[2] */
      pMessageboxWidget->slotChatSearch( 1, slCommand[2] );
	    slotChangeTab( 1 );
    }
    else if ( slCommand[1] == "MEMO" )
    {
    }
  }
  else if ( slCommand[0] == "QUIT" )
  {
    close();
  }
}

void messagebox::slotOpenMenu()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
		if ( pMessageboxWidget->pListViews->getCurrentItem() == 0 )
		{
			KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
			return;
		}
	}
	else
	{
		if ( pMessageboxWidget->pListViews_2->getCurrentItem() == 0 )
		{
			KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
			return;
		}
	}
	pMessageboxWidget->slotMouseRight( 1 );
}

void messagebox::slotSaveMenu()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
#ifdef NETDEBUG
		kdDebug() << "[쪽지 저장]" << endl;
#endif
		if ( pMessageboxWidget->pListViews->getCurrentItem() == 0 )
		{
			KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
			return;
		}
		pMessageboxWidget->slotMemoSave();
	}
	else
	{
#ifdef NETDEBUG
		kdDebug() << "[대화 저장]" << endl;
#endif
		if ( pMessageboxWidget->pListViews_2->getCurrentItem() == 0 )
		{
			KMessageBox::information( this, i18n("먼저 선택을 하셔야 됩니다."), i18n("알림") );
			return;
		}
		pMessageboxWidget->slotChatSave();
	}
}

void messagebox::slotNewMenu()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
		pMessageboxWidget->slotMemoWrite();
	}
	else
	{
		pMessageboxWidget->slotGoChat();
	}
}

void messagebox::slotAlwaysTop( bool bAlwaysTop )
{
	int flags = getWFlags();
	
	/*! 메뉴의 항상위 채크 */
	if ( bAlwaysTop )
	{
		if( !testWFlags(Qt::WStyle_StaysOnTop) )
		{
			flags |= Qt::WStyle_StaysOnTop;
			QPoint p(geometry().x(),geometry().y());
			reparent(0,flags,p,true);
		}
	}
	else
	{
		if( testWFlags(Qt::WStyle_StaysOnTop) )
		{
			flags ^= Qt::WStyle_StaysOnTop;
			QPoint p(geometry().x(),geometry().y());
			reparent(0,flags,p,true);
		}
	}
}

void messagebox::slotSetup()
{
}

void messagebox::slotFindMenu()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
		pMessageboxWidget->slotMemoFind();
	}
	else
	{
		pMessageboxWidget->slotChatFind();
	}
}

void messagebox::slotSelectAll()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
		pMessageboxWidget->pListViews->messages->selectAll ( TRUE );
	}
	else
	{
		pMessageboxWidget->pListViews_2->messages->selectAll ( TRUE );
	}
}

void messagebox::slotRefreshMenu()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
		pMessageboxWidget->slotMemoRefresh();
	}
	else
	{
		pMessageboxWidget->slotChatRefresh();
	}
}

void messagebox::slotGoNateDotComMenu()
{
	/*! 티켓값으로 로그인 후 페이지 열기 */
	LNMUtils::openURL( "http://www.nate.com/" );
}

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

void messagebox::slotGoHotTipMenu()
{
	LNMUtils::openURL("http://nateonweb.nate.com/help/guide_hottip_v3_main.html");
}

void messagebox::slotGoFaqMenu()
{
	LNMUtils::openURL("http://nateonweb.nate.com/help/guide_faqsearch_list.html");
}

void messagebox::slotGoAboutMenu()
{
	
}

void messagebox::slotDelete()
{
	if ( pMessageboxWidget->tabWidget2->currentPageIndex() == 0 )
	{
		pMessageboxWidget->slotMemoDelete();
	}
	else
	{
		pMessageboxWidget->slotChatDelete();
	}
}

void messagebox::slotChangeTab(int nTab)
{
	if ( nTab == 0 )
	{
		pNewAction->setText (i18n("새 메시지(&M)"));
		pReplyMemoAction->setEnabled( TRUE );
		pReplyAllMemoAction->setEnabled( TRUE );
		pForwardMemoAction->setEnabled( TRUE );
	}
	else
	{
		pNewAction->setText (i18n("새 대화(&T)"));
		pReplyMemoAction->setEnabled( FALSE );
		pReplyAllMemoAction->setEnabled( FALSE );
		pForwardMemoAction->setEnabled( FALSE );
	}
}

void messagebox::setDefaultBrowser(const QString s)
{
	stConfig.defaultwebbrowser = s;
	// kdDebug() << "MSGBOX Default WB : ["<< s << "]" << endl;
	if ( stConfig.defaultwebbrowser == QString::fromUtf8("none") ){
		stConfig.usedefaultwebbrowser = FALSE;
	} else {
		stConfig.usedefaultwebbrowser = TRUE;
	}
}


#include "messagebox.moc"
