/***************************************************************************
                          whtmlpart.cpp  -  description
                             -------------------
    begin                : Fri Aug 18 2000
    copyright            : (C) 2000 by Dmitry Poplavsky & Alexander Yakovlev & Eric Laffoon <pdima@users.sourceforge.net,yshurik@linuxfan.com,sequitur@easystreet.com>
                           (C) 2002, 2004, 2005 Andras Mantia <amantia@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.                                   *
 *                                                                         *
 ***************************************************************************/
 
//qt includes
#include <tqfileinfo.h>
#include <tqtextcodec.h>

//kde includes
#include <tdeconfig.h>
#include <kdebug.h>
#include <tdeversion.h>
#include <tdehtml_settings.h>
#include <tdehtmlview.h>
#include <tdelocale.h>
#include <tdepopupmenu.h>
#include <tdetempfile.h>

//app includes
#include "whtmlpart.h"
#include "resource.h"

WHTMLPart::WHTMLPart(TQWidget *parentWidget, const char *widgetName, bool enableViewSource, 
            TQObject *parent, const char *name, GUIProfile prof)
  : TDEHTMLPart(parentWidget, widgetName, parent, name, prof), m_contextMenu(0)
{
  //kdDebug(24000) << "WHTMLPart: " << parentWidget << " " << widgetName << " " << parent << " " << name << this << endl;
   hpos = 0;
   // get settings from konq.
   TDEConfig konqConfig("konquerorrc");

   konqConfig.setGroup("HTML Settings");

   const TDEHTMLSettings * set = settings();

   const_cast<TDEHTMLSettings*>(set)->init( &konqConfig, false );
   view()->installEventFilter(this);
   
   m_enableViewSource = enableViewSource;
   if (m_enableViewSource)
   {
    m_contextMenu = new TDEPopupMenu(parentWidget);
    m_contextMenu->insertItem(i18n("View &Document Source"), this, TQT_SLOT(slotViewSource()));
    
    connect(this, TQT_SIGNAL(popupMenu(const TQString&, const TQPoint&)), TQT_SLOT(popupMenu(const TQString&, const TQPoint&)));
   }
   connect(browserExtension(), TQT_SIGNAL(openURLRequest (const KURL &, const KParts::URLArgs &)), this, TQT_SLOT(openURL(const KURL&)));

//   setCharset( konqConfig.readEntry("DefaultEncoding") );
//   setEncoding( konqConfig.readEntry("DefaultEncoding") );
//   setStandardFont( konqConfig.readEntry("StandardFont") );
//   setFixedFont( konqConfig.readEntry("FixedFont") );
//   updateFontSize( konqConfig.readNumEntry("FontSize"));
}

WHTMLPart::~WHTMLPart()
{
}

void WHTMLPart::setPreviewedURL(const KURL &url)
{
  m_previewedURL = url;
}

bool WHTMLPart::openURL(const KURL& url)
{
  if (url == m_previewedURL)
  {
    KURL previewURL = url;
    previewURL.setFileName("preview-" + url.fileName());
    return TDEHTMLPart::openURL(previewURL);
  } else
    return TDEHTMLPart::openURL(url);
}

void  WHTMLPart::urlSelected ( const TQString &url, int button, int state, const TQString &target, KParts::URLArgs args)
{
  TDEHTMLPart::urlSelected (url, button, state, target, args);
  KURL cURL = completeURL( url );
//  alternative not tested but used in tdevelop !
//  KURL cURL=KURL(baseURL(),url);
  if (target.isEmpty() || (target == "_self") || (target == "_top") || (target == "_blank") || (target == "_parent") )
    openURL( cURL ) ;
  addToHistory( cURL.url() );
}

void WHTMLPart::forward()
{
  if ( forwardEnable() ) {
    hpos++;
    openURL( KURL( history.at(hpos) ) );

    emit updateStatus( backEnable() , forwardEnable() );
  }
}


void WHTMLPart::back()
{
  if (backEnable())
  {
    hpos--;
    openURL(KURL(history.at(hpos)));

    emit updateStatus(backEnable(), forwardEnable());
  }
}


void WHTMLPart::addToHistory(const TQString &url)
{

   if ( history.count() > 0 )
     while ( hpos < history.count()-1  )
         history.removeLast();

   if ( !history.isEmpty() ) hpos++;

   history.append(url.ascii());

   hpos = history.count()-1;

   emit updateStatus( backEnable() , forwardEnable() );

}


bool WHTMLPart::backEnable()
{
   return hpos > 0;
}


bool WHTMLPart::forwardEnable()
{
   return hpos < history.count()-1;
}

KParts::ReadOnlyPart *WHTMLPart::createPart( TQWidget * parentWidget, const char *widgetName, 
                                            TQObject *parent, const char *name,
                                            const TQString &, TQString &,
                                            TQStringList &, const TQStringList &)
{
  //kdDebug(24000) << "Create WHTMLPart: " << parentWidget << " " << widgetName << " " << parent << " " << name << endl;
  return new WHTMLPart(parentWidget, widgetName, m_enableViewSource, parent, name);
}

bool WHTMLPart::eventFilter(TQObject *watched, TQEvent *e)
{
  if (TQT_BASE_OBJECT(watched) == TQT_BASE_OBJECT(view()) && e->type() == TQEvent::FocusOut && (!m_contextMenu || !m_contextMenu->hasFocus()))
    emit previewHasFocus(false);
  else
  if (TQT_BASE_OBJECT(watched) == TQT_BASE_OBJECT(view()) && e->type() == TQEvent::FocusIn)
    emit previewHasFocus(true);
  return false;
}

void WHTMLPart::popupMenu(const TQString &/*url*/, const TQPoint &point)
{
  m_contextMenu->popup(point);  
}

void WHTMLPart::slotViewSource()
{  
  KTempFile *tmpFile = new KTempFile(tmpDir + "-preview-", ".html");
  TQString tempFileName = TQFileInfo(*(tmpFile->file())).filePath();
  tmpFile->setAutoDelete(true);
  tmpFile->textStream()->setCodec(TQTextCodec::codecForName("utf8"));
  *(tmpFile->textStream()) << documentSource();
  tmpFile->close();
  tempFileList.append(tmpFile);
  emit showPreview(false);
  emit openFile(KURL::fromPathOrURL(tmpFile->name()), "utf8", true);
}

#include "whtmlpart.moc"