#include <kiconloader.h>
#include <kstddirs.h>
#include <kapp.h>
#include <kaction.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <klibloader.h>
#include <kstdaction.h>

#include "kgv_miniwidget.h"
#include "kgv_view.h"

#include "kgvshell.moc"

//TODO -- disable GUI when no file
//TODO -- don't stay open when no file, go directly to KFileDialog

KGVShell::KGVShell()
{

 // We already link to libkghostview !
#if 0
  // Try to find libkghostview
  KLibFactory *factory = KLibLoader::self()->factory( "libkghostview" );
  if (factory)
  {
    // Create the part
    m_gvpart = (KGVPart *)factory->create( this, "kgvpart",
               "KParts::ReadOnlyPart" );
  }
  else
    {
      //TODO - KNotify
      KMessageBox::error(this, "No libkghostview found !");
      exit(1);
      return;
    }
#else
  m_gvpart = new KGVPart( false, this, "kgvpart", this, "kgvpart" );
#endif  // if 0


  statedep = new KActionCollection;

  //File
  openact = KStdAction::open ( this, SLOT(slotFileOpen()),
		     actionCollection());
  recent =
    KStdAction::openRecent ( this, SLOT (openURL (const KURL &)),
			     actionCollection() );

  statedep->insert
    ( KStdAction::print ( m_gvpart->miniWidget(), SLOT (print()),
			  actionCollection()) );
  KStdAction::quit ( this, SLOT (slotQuit()),
		     actionCollection());

  //View
  statedep->insert 
    ( KStdAction::redisplay ( m_gvpart->miniWidget(), SLOT (redisplay()),
			      actionCollection()) );
  
  statedep->insert 
    ( new KAction (i18n("&Fit To Page Width"), 0, this,
		   SLOT (slotFitToPage()), actionCollection(),
		   "fit_to_page") );
  

  //Settings

  showtoolbar =
    KStdAction::showToolbar ( this, SLOT(slotShowToolBar()),
			      actionCollection());
  
  showstatusbar =
    KStdAction::showStatusbar ( this, SLOT(slotShowStatusBar()),
				actionCollection());

  // Just save them automatically is destructor. (TODO: of kgv_view!)
  //KStdAction::saveOptions ( this, SLOT (slotWriteSettings()),			    actionCollection());


  setXMLFile( "kghostviewui.rc" );

  //We could, at the user's option, make this connection and kghostview
  // will always resize to fit the width of the page.  But, for now,
  // let's not.
  //  connect ( m_gvpart->widget(), SIGNAL (sizeHintChanged()),	    this, SLOT (slotResize ()) );

  // Set the main widget
  setCentralWidget( m_gvpart->widget() );
  // Integrate its GUI
  createGUI( m_gvpart );

  readSettings();
  enableStateDepActions( false );

  //TODO: use last size
  resize (width0, height0);

  // Make sure the view has the keyboard focus.
  m_gvpart->widget()->setFocus();
}

KGVShell::~KGVShell()
{
    writeSettings();
    delete m_gvpart;
}

void
KGVShell::slotQuit()
{
    kapp->closeAllWindows();
}

void
KGVShell::readSettings()
{
    KConfig *config = KGlobal::config();

    config->setGroup( "General" );

    showtoolbar->setChecked( config->readBoolEntry( "ShowToolBar", true ) );
    slotShowToolBar();
    
    showstatusbar->setChecked( config->readBoolEntry( "ShowStatusBar", true ));
    slotShowStatusBar();

    width0 = config->readUnsignedNumEntry( "WindowWidth", 600 );
    height0 = config->readUnsignedNumEntry( "WindowHeight", 300 );

    recent->loadEntries( config );
}

void
KGVShell::writeSettings()
{
    KConfig *config = KGlobal::config();

    config->setGroup( "General" );
    config->writeEntry( "ShowToolBar", showtoolbar->isChecked() );
    config->writeEntry( "ShowStatusBar", showstatusbar->isChecked() );
    config->writeEntry( "WindowWidth", width() );
    config->writeEntry( "WindowHeight", height() );

    recent->saveEntries( config );

    config->sync();
}

void
KGVShell::openURL( const KURL & url )
{
    if( m_gvpart->openURL( url ) ) {
	recent->addURL (url);
	enableStateDepActions( true );
    }
}

void
KGVShell::openStdin()
{
    if( m_gvpart->openStdin() )
	enableStateDepActions( true );
}

void
KGVShell::slotFileOpen()
{
  KURL url = KFileDialog::
    getOpenURL( cwd,
		i18n("*.ps *.ps.gz|Postscript files\n"
		"*.eps *.eps.gz|Encapsulated Postscript files\n"
		"*.pdf|Portable Document Format files") );

  if( !url.isEmpty() )
     openURL( url );
}

void
KGVShell::slotFitToPage()
{
    resize( m_gvpart->widget()->width() - 
	    m_gvpart->psView()->viewport()->width() +
	    m_gvpart->psView()->psWidget()->width(), 
	    height() );
}

void
KGVShell::slotResize()
{
  resize (m_gvpart->psView()->sizeHint().width(), height());
}

void
KGVShell::slotShowStatusBar()
{
    if( showstatusbar->isChecked() )
	statusBar()->show();
    else
	statusBar()->hide();
}

void
KGVShell::slotShowToolBar()
{
    KToolBar *bar = toolBar("mainToolBar");

    if( bar != 0 ) {
	if( showtoolbar->isChecked() ) {
	    bar->setFullSize( false );
	    bar->show();
	}
	else
	    bar->hide();
    }
}

void
KGVShell::enableStateDepActions( bool enable )
{
  int count = statedep->count();
  for ( int i = 0; i < count; i++ )
    {
      statedep->action( i )->setEnabled( enable );
    }


  if (!enable)
    openact->setEnabled (true);
}
