/***************************************************************************
                       kbbmainwindow.cpp  -  description
                             -------------------
    copyright            : (C) 2001 by Martijn Klingens
    email                : klingens@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kbbmainwindow.h"

#include <tqlabel.h>
#include <tqlayout.h>
#include <tqmultilineedit.h>
#include <tqprogressbar.h>
#include <tqpushbutton.h>
#include <tqtextview.h>
#include <tqwidgetstack.h>

#include <tdeaction.h>
#include <kbookmarkmenu.h>
#include <kcombobox.h>
#include <tdeconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kinputdialog.h>
#include <klineedit.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <tdemenubar.h>
#include <tdemessagebox.h>
#include <kstatusbar.h>
#include <kstdaction.h>
#include <kstdguiitem.h>
#include <kedittoolbar.h>


#include "bugcommand.h"
#include "bugserver.h"
#include "bugserverconfig.h"
#include "bugsystem.h"
#include "centralwidget.h"
#include "cwbugdetails.h"
#include "kbbbookmarkmanager.h"
#include "kbbprefs.h"
#include "kfinddialog.h"
#include "packageselectdialog.h"
#include "preferencesdialog.h"

#define ID_STATUS_MSG 1

using namespace KBugBusterMainWindow;

class TextViewer : public KDialogBase
{
  public:
    TextViewer( const TQString &title, TQWidget *parent = 0 )
      : KDialogBase( Plain, title, Ok, Ok, parent, 0,
                     false )
    {
      TQFrame *topFrame = plainPage();

      TQBoxLayout *topLayout = new TQVBoxLayout( topFrame );

      mTextView = new TQTextEdit( topFrame );
      mTextView->setReadOnly( true );
      mTextView->setTextFormat( PlainText );
      topLayout->addWidget( mTextView );

      resize( 600, 400 );
    }

    void setText( const TQString &text )
    {
      mTextView->setText( text );
    }

  private:
    TQTextEdit *mTextView;
};

KBookmarkManager* KBBBookmarkManager::s_bookmarkManager;

KBBMainWindow::KBBMainWindow( const TQCString &initialPackage,
                              const TQCString &initialComponent,
                              const TQCString &initialBug,
                              TQWidget * , const char * name )
  : TDEMainWindow( 0, name ), mPreferencesDialog( 0 ), mResponseViewer( 0 ),
    mBugSourceViewer( 0 ), mPackageSelectDialog( 0 )
{
    BugSystem::self()->setCurrentServer( KBBPrefs::instance()->mCurrentServer );

    m_statusLabel = new TQLabel( i18n( "Welcome to <b>KBugBuster</b>." ), statusBar() );
    m_statusLabel->setMaximumHeight( statusBar()->fontMetrics().height() + 6 );
    m_statusLabel->setIndent( KDialog::marginHint() / 2 );
    statusBar()->addWidget( m_statusLabel, 1 );

    m_mainWidget = new CentralWidget( initialPackage, initialComponent,
                                      initialBug, this );
    setCentralWidget( m_mainWidget );

    initActions();

    m_progressBar = new TQProgressBar( 100, statusBar() );
    m_progressBar->setCenterIndicator( true );
    m_progressBar->setMinimumWidth( 150 );
    m_progressBar->setMaximumHeight( statusBar()->fontMetrics().height() + 6 );
    statusBar()->addWidget( m_progressBar );
    connect( m_mainWidget, TQ_SIGNAL( resetProgressBar() ),
             m_progressBar, TQ_SLOT( reset() ) );
    connect( m_mainWidget, TQ_SIGNAL( searchPackage() ),
             this, TQ_SLOT( searchPackage() ) );
    connect( m_mainWidget, TQ_SIGNAL( searchBugNumber() ),
             this, TQ_SLOT( searchBugNumber() ) );

    connect( BugSystem::self(), TQ_SIGNAL( infoMessage( const TQString & ) ),
             TQ_SLOT( slotStatusMsg( const TQString & ) ) );

    connect( BugSystem::self(), TQ_SIGNAL( infoMessage( const TQString & ) ),
             TQ_SLOT( slotStatusMsg( const TQString & ) ) );
    connect( BugSystem::self(), TQ_SIGNAL( infoPercent( unsigned long ) ),
             TQ_SLOT( slotSetPercent( unsigned long ) ) );

    m_mainWidget->readConfig();
}

KBBMainWindow::~KBBMainWindow()
{
//    kdDebug() << "KBBMainWindow::~KBBMainWindow()" << endl;
    delete m_pBookmarkMenu;

    m_mainWidget->writeConfig();

    KBBPrefs::instance()->writeConfig();
}

void KBBMainWindow::initActions()
{
    // Prepare and create XML GUI
    fileQuit          = KStdAction::quit( this,
                        TQ_SLOT( close() ), actionCollection() );
    fileQuit->setToolTip( i18n( "Quit KBugBuster" ) );

    new TDEAction( i18n("See &Pending Changes"), "contents", 0, this, TQ_SLOT( slotListChanges() ),
                 actionCollection(), "file_seechanges" );
    new TDEAction( i18n("&Submit Changes"), "mail-send", 0, this, TQ_SLOT( slotSubmit() ),
                 actionCollection(), "file_submit" );

    reloadpacklist = new TDEAction( i18n("Reload &Product List"), "reload", CTRL+TQt::Key_F5, m_mainWidget, TQ_SLOT( slotReloadPackageList() ),
                 actionCollection(), "reload_packagelist" );
    reloadpack= new TDEAction( i18n("Reload Bug &List (for current product)"), "reload", TQt::Key_F5, m_mainWidget, TQ_SLOT( slotReloadPackage() ),
                 actionCollection(), "reload_package" );
    reloadbug = new TDEAction( i18n("Reload Bug &Details (for current bug)"), "reload", SHIFT+TQt::Key_F5, m_mainWidget, TQ_SLOT( slotReloadBug() ),
                 actionCollection(), "reload_bug" );
    loadMyBugs = new TDEAction( i18n( "Load &My Bugs List" ), 0, m_mainWidget, TQ_SLOT( slotLoadMyBugs() ),
                 actionCollection(), "load_my_bugs" );
    reloadall = new TDEAction( i18n("Load All Bug Details (for current product)"), TQt::Key_F6, m_mainWidget, TQ_SLOT( slotRetrieveAllBugDetails() ), actionCollection(), "load_allbugs" );
    new TDEAction( i18n("Extract &Attachments"), "document-save", TQt::Key_F4, m_mainWidget, TQ_SLOT( slotExtractAttachments() ),
                 actionCollection(), "extract_attachments" );

    new TDEAction( i18n("Clear Cache"), 0, this, TQ_SLOT( clearCache() ),
                 actionCollection(), "clear_cache" );

    new TDEAction( i18n("&Search by Product..."), "goto", CTRL+TQt::Key_P, this,
                 TQ_SLOT( searchPackage() ), actionCollection(), "search_package" );
    new TDEAction( i18n("Search by Bug &Number..."), "filefind", CTRL+TQt::Key_N, this,
                 TQ_SLOT( searchBugNumber() ), actionCollection(), "search_bugnumber" );
    // For now "Description" searches by title. Maybe later we can have a
    // full-text search interfacing bugs.trinitydesktop.org and rename the current one to "By Title".
    new TDEAction( i18n("Search by &Description...") ,"edit-find", CTRL+TQt::Key_D, this,
                 TQ_SLOT( searchDescription() ), actionCollection(), "search_description" );

//    new TDEAction( i18n("&Merge"), "view_remove", CTRL+TQt::Key_M, m_mainWidget,
//                 TQ_SLOT( mergeBugs() ), actionCollection(), "cmd_merge" );
//    new TDEAction( i18n("&Unmerge"), "view_top_bottom", CTRL+SHIFT+TQt::Key_M, m_mainWidget,
//                 TQ_SLOT( unmergeBugs() ), actionCollection(), "cmd_unmerge" );
    new TDEAction( i18n("C&lose..."), "edittrash", CTRL+TQt::Key_L, m_mainWidget,
                 TQ_SLOT( closeBug() ), actionCollection(), "cmd_close" );
//    new TDEAction( i18n("Clos&e Silently"), "edittrash", CTRL+TQt::Key_E, m_mainWidget,
//                 TQ_SLOT( closeBugSilently() ), actionCollection(), "cmd_close_silently" );
    new TDEAction( i18n("Re&open"), "idea", CTRL+TQt::Key_O, m_mainWidget,
                 TQ_SLOT( reopenBug() ), actionCollection(), "cmd_reopen" );
//    new TDEAction( i18n("Re&assign..."), "folder-new", CTRL+TQt::Key_A, m_mainWidget,
//                 TQ_SLOT( reassignBug() ), actionCollection(), "cmd_reassign" );
//    new TDEAction( i18n("Change &Title..."), "format-text-underline", CTRL+TQt::Key_T, m_mainWidget,
//                 TQ_SLOT( titleBug() ), actionCollection(), "cmd_title" );
//    new TDEAction( i18n("Change &Severity..."), "edit", CTRL+TQt::Key_S, m_mainWidget,
//                 TQ_SLOT( severityBug() ), actionCollection(), "cmd_severity" );
    new TDEAction( i18n("&Reply..."), "mail-reply-all",CTRL+TQt::Key_R , m_mainWidget,
                 TQ_SLOT( replyBug() ), actionCollection(), "cmd_reply" );
    new TDEAction( i18n("Reply &Privately..."), "mail-reply-sender", CTRL+TQt::Key_I, m_mainWidget,
                 TQ_SLOT( replyPrivateBug() ), actionCollection(), "cmd_replyprivate" );

    KStdAction::showMenubar(this, TQ_SLOT( slotToggleMenubar() ), actionCollection() );
    createStandardStatusBarAction();
    setStandardToolBarMenuEnabled(true);

    m_disconnectedAction = new TDEToggleAction( i18n("&Disconnected Mode"), 0,
                                              this,
                                              TQ_SLOT( slotDisconnectedAction() ),
                                              actionCollection(),
                                              "settings_disconnected" );
    m_disconnectedAction->setChecked( BugSystem::self()->disconnected() );

    // Bookmarks menu
    m_pamBookmarks = new TDEActionMenu( i18n( "&Bookmarks" ), "bookmark", actionCollection(), "bookmarks" );
    m_pBookmarkMenu = new KBookmarkMenu( KBBBookmarkManager::self(), this, m_pamBookmarks->popupMenu(), actionCollection(), true );

    KStdAction::preferences( this, TQ_SLOT(preferences()), actionCollection() );

    TDEToggleAction *toggleTmp =  new TDEToggleAction( i18n("Show Closed Bugs"), "application-x-trash", 0, this, TQ_SLOT( slotToggleDone() ),
                 actionCollection(), "cmd_toggle_done" );
    toggleTmp->setCheckedState(i18n("Hide Closed Bugs"));
    toggleTmp->setChecked( KBBPrefs::instance()->mShowClosedBugs );

    toggleTmp =new TDEToggleAction( i18n("Show Wishes"), "bookmark", 0, this, TQ_SLOT( slotToggleWishes() ),
                 actionCollection(), "cmd_toggle_wishes" );
    toggleTmp->setCheckedState(i18n("Hide Wishes"));
    toggleTmp->setChecked(KBBPrefs::instance()->mShowWishes);

    mSelectServerAction = new TDESelectAction( i18n( "Select Server" ), 0, 0,
                                             this,
                                             TQ_SLOT( slotSelectServer() ),
                                             actionCollection(),
                                             "select_server" );

    setupSelectServerAction();

    if ( KBBPrefs::instance()->mDebugMode ) {
      new TDEAction( i18n("Show Last Server Response..."), 0 , this,
                   TQ_SLOT( showLastResponse() ), actionCollection(),
                   "debug_lastresponse" );
      new TDEAction( i18n("Show Bug HTML Source..."), 0 , this,
                   TQ_SLOT( showBugSource() ), actionCollection(),
                   "debug_showbugsource" );
    }

    setupGUI( (ToolBar | Keys | StatusBar | Save | Create ), "kbugbusterui.rc" );
}

void KBBMainWindow::slotToggleMenubar()
{
    if ( !hasMenuBar() )
        return;

    if ( menuBar()->isVisible() )
        menuBar()->hide();
    else
        menuBar()->show();
}

void KBBMainWindow::setupSelectServerAction()
{
    TQStringList servers;
    int current = -1;
    TQValueList<BugServer *> serverList = BugSystem::self()->serverList();
    TQValueList<BugServer *>::ConstIterator it;
    for ( it = serverList.begin(); it != serverList.end(); ++it ) {
      TQString name = (*it)->serverConfig().name();
      servers.append( name );
      if ( name == KBBPrefs::instance()->mCurrentServer ) {
        current = servers.count() - 1;
      }
    }
    mSelectServerAction->setItems( servers );
    if ( current >= 0 ) {
      mSelectServerAction->setCurrentItem( current );
    }
}

TQString KBBMainWindow::currentURL() const
{
  TQString number=m_mainWidget->currentNumber();

  if (number.isEmpty())
    return "";
  else
    return "bug:"+number;
}

TQString KBBMainWindow::currentTitle() const
{
  return "#"+m_mainWidget->currentNumber()+": "+m_mainWidget->currentTitle();
}

void KBBMainWindow::openBookmarkURL( const TQString & url )
{
    if ( url.left(4)=="bug:" ) {
      TQString bugnumber = url.mid(4);
      m_mainWidget->slotRetrieveBugDetails( Bug::fromNumber( bugnumber ) );
    }
}

// --- SLOT IMPLEMENTATIONS -------------------------------------------------

void KBBMainWindow::slotDisconnectedAction()
{
    BugSystem::self()->setDisconnected( m_disconnectedAction->isChecked() );

    bool enable = !m_disconnectedAction->isChecked();

    reloadpacklist->setEnabled( enable );
    reloadpacklist->setEnabled( enable );
    reloadpack->setEnabled( enable );
    reloadbug->setEnabled( enable );
    reloadall->setEnabled( enable );
    loadMyBugs->setEnabled( enable );
}

void KBBMainWindow::slotStatusMsg( const TQString &text )
{
    // Change status message permanently
    m_statusLabel->setText( text );
}

void KBBMainWindow::slotSubmit()
{
    BugSystem::self()->sendCommands();
}

void KBBMainWindow::slotListChanges()
{
    TQStringList list = BugSystem::self()->server()->listCommands();

    if (list.count() > 0)
    {
       int ret = KMessageBox::questionYesNoList( this, i18n("List of pending commands:"),
                                              list, TQString(), KStdGuiItem::clear(), KStdGuiItem::close() );
       if ( ret == KMessageBox::Yes )
       {
           // Ask for confirmation, it's too easy to click the wrong button in the above dlg box
           if ( KMessageBox::warningContinueCancel( this, i18n("Do you really want to delete all commands?"),
                               i18n("Confirmation Required"), KGuiItem( i18n("&Delete"), "edit-delete"), "clearcommands", true)
                   == KMessageBox::Continue )
               BugSystem::self()->clearCommands();
       }
   }
   else
   {
       KMessageBox::information( this, i18n("There are no pending commands.") );
   }
}

void KBBMainWindow::slotSetPercent( unsigned long percent )
{
    // TDEIO::Job::percent() shouldn't return an unsigned long. - Frerich
    m_progressBar->setProgress( percent );
}

void KBBMainWindow::searchPackage()
{
    if ( !mPackageSelectDialog ) {
        mPackageSelectDialog = new PackageSelectDialog( this );
    }
    mPackageSelectDialog->setPackages( BugSystem::self()->packageList() );
    BugServerConfig cfg = BugSystem::self()->server()->serverConfig();
    TQStringList recent = cfg.recentPackages();
    kdDebug() << "MainWindow RECENT: " << recent.join(",") << endl;
    mPackageSelectDialog->setRecentPackages( recent );

    mPackageSelectDialog->exec();
    Package package = mPackageSelectDialog->selectedPackage();

    if ( package.isNull() ) {
        return;
    }

    TQString component = mPackageSelectDialog->selectedComponent();
    m_mainWidget->slotRetrieveBugList( package.name(), component );
}

void KBBMainWindow::searchBugNumber()
{
    bool ok = false;
    TQString result = KInputDialog::getText( i18n("Search for Bug Number"),
                                            i18n("Please enter a bug number:"),
                                            TQString(), &ok, this );
    if ( ok ) {
      //Strip whitespace and # if needed
      result = result.stripWhiteSpace();
      if (result[0]=='#')
        result = result.mid(1);
    }

    if ( ok && !result.isEmpty()) {
        // ### bad way to instantiate a bug! doesn't get us the details!
        // Right - but do we need the details in this case ? There's no listview entry here... (DF)
        m_mainWidget->slotRetrieveBugDetails( Bug::fromNumber( result ) );
    }
}

void KBBMainWindow::searchDescription()
{
    kdDebug() << "KBBMainWindow::searchDescription()." << endl;
    //KMessageBox::sorry(this,i18n("searchDescription(): to be implemented."),i18n("Not implemented"));
    KFindDialog dlg( this );
    if ( dlg.exec() == KDialogBase::Accepted )
        m_mainWidget->searchBugByTitle( dlg.options(), dlg.pattern() );
}

bool KBBMainWindow::queryClose()
{
    if ( ! BugSystem::self()->server()->commandsPending() ) return true;

    int result = KMessageBox::warningYesNoCancel(this,i18n("There are unsent bug commands."
                                                           " Do you want to send them now?"), TQString(), i18n("Send"), i18n("Do Not Send"));
    if ( result == KMessageBox::Cancel ) return false;
    if ( result == KMessageBox::Yes ) {
        BugSystem::self()->sendCommands();
    }
    return true;
}

void KBBMainWindow::preferences()
{
    if (!mPreferencesDialog) {
      mPreferencesDialog  = new PreferencesDialog(this);
      connect( mPreferencesDialog, TQ_SIGNAL( configChanged() ),
               TQ_SLOT( setupSelectServerAction() ) );
      connect( mPreferencesDialog, TQ_SIGNAL( configChanged() ),
               m_mainWidget, TQ_SLOT( slotReloadPackage() ) );
    }
    mPreferencesDialog->show();
    mPreferencesDialog->raise();
}

void KBBMainWindow::updatePackage()
{
    m_mainWidget->updatePackage();
}

void KBBMainWindow::slotToggleDone()
{
  KBBPrefs::instance()->mShowClosedBugs=!(KBBPrefs::instance()->mShowClosedBugs);
  updatePackage();
}

void KBBMainWindow::slotToggleWishes()
{
  KBBPrefs::instance()->mShowWishes=!(KBBPrefs::instance()->mShowWishes);
  updatePackage();
}

void KBBMainWindow::slotSelectServer()
{
  m_mainWidget->writeConfig();

  TQString currentServer = mSelectServerAction->currentText();

  BugSystem::self()->setCurrentServer( currentServer );

  m_mainWidget->initialize();
}

void KBBMainWindow::showLastResponse()
{
  if ( !mResponseViewer ) {
    mResponseViewer = new TextViewer( i18n("Last Server Response"), this );
  }

  mResponseViewer->setText( BugSystem::lastResponse() );

  mResponseViewer->show();
  mResponseViewer->raise();
}

void KBBMainWindow::showBugSource()
{
  if ( !mBugSourceViewer ) {
    mBugSourceViewer = new TextViewer( i18n("Bug HTML Source"), this );
  }

  mBugSourceViewer->setText( m_mainWidget->bugDetailsWidget()->source() );

  mBugSourceViewer->show();
  mBugSourceViewer->raise();
}

void KBBMainWindow::clearCache()
{
  BugSystem::self()->server()->cache()->clear();
}

#include "kbbmainwindow.moc"
