/* This file is part of the KDE project
   Copyright (C) 2003-2004 Jaroslaw Staniek <js@iidea.pl>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

/*!
 Temporary moved from TQKW KFileDialog implementation.
 TODO: move to KDElibs/win32 KFileDialog wrapper
*/

#include "KexiStartupFileDialog.h"
#include <kexiutils/utils.h>

#include <kiconloader.h>
#include <kdebug.h>
#include <tderecentdirs.h>

#include <tqobjectlist.h>
#include <tqlineedit.h>

#include <win/win32_utils.h>

//! @internal
class KexiStartupFileDialogBasePrivate
{
	public:
		KexiStartupFileDialogBasePrivate()
		{}
		KFile::Mode mode;
		TQString kde_filters;
		TQStringList mimetypes;
};

KexiStartupFileDialogBase::KexiStartupFileDialogBase(
	const TQString & dirName, const TQString & filter, 
	TQWidget * parent, const char * name, bool modal )
 : TQFileDialog( realStartDir(dirName), filter, parent, name, modal )
 , d(new KexiStartupFileDialogBasePrivate())
{
//	TQString _dirName = dirName;
	TQString _dirName = dirPath();
	//make default 'My Documents' folder
//TODO: store changes in the app's config file?
	if (_dirName.isEmpty())
		_dirName = TDEGlobalSettings::documentPath();

	init(_dirName, filter, parent);

	//find "OK" button
	TQObjectList *l = queryList( TQPUSHBUTTON_OBJECT_NAME_STRING, "OK", false );
	m_okBtn = dynamic_cast<TQPushButton*>(l->first());
	delete l;
	l = queryList( TQLINEEDIT_OBJECT_NAME_STRING, "name/filter editor", false );
	m_lineEdit = dynamic_cast<TQLineEdit*>(l->first());
	delete l;

	adjustSize();
}

KexiStartupFileDialogBase::~KexiStartupFileDialogBase()
{
}

void KexiStartupFileDialogBase::init(const TQString& startDir, const TQString& filter, TQWidget* widget)
{
//TODO    initStatic();
//TODO    d = new KFileDialogPrivate();

//(js)    d->boxLayout = 0;
//TODO    d->keepLocation = false;
//TODO    d->operationMode = Opening;
    setMode(KFile::File | KFile::ExistingOnly); //(js) default: open action
    setIcon( TDEGlobal::iconLoader()->loadIcon("fileopen", TDEIcon::Desktop) );
		setDir(TQDir(startDir));
//TODO    d->hasDefaultFilter = false;
//TODO    d->hasView = false;
//(js)    d->mainWidget = new TQWidget( this, "KFileDialog::mainWidget");
//(js)    setMainWidget( d->mainWidget );
//(js)    d->okButton = new KPushButton( KStdGuiItem::ok(), d->mainWidget );
//(js)    d->okButton->setDefault( true );
//(js)    d->cancelButton = new KPushButton(KStdGuiItem::cancel(), d->mainWidget);
//(js)    connect( d->okButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOk() ));
//(js)    connect( d->cancelButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotCancel() ));
//(js)    d->customWidget = widget;
//(js)    d->autoSelectExtCheckBox = 0; // delayed loading
//TODO    d->autoSelectExtChecked = false;
//(js)    d->urlBar = 0; // delayed loading
//TODO    TDEConfig *config = TDEGlobal::config();
//TODO    TDEConfigGroupSaver cs( config, ConfigGroup );
//TODO    d->initializeSpeedbar = config->readBoolEntry( "Set speedbar defaults",
//TODO                                                   true );
//TODO    d->completionLock = false;

//TODO    TQtMsgHandler oldHandler = tqInstallMsgHandler( silenceTQToolBar );
//TODO    toolbar = 0; //(js)
//(js)    toolbar = new TDEToolBar( d->mainWidget, "KFileDialog::toolbar", true);
//(js)    toolbar->setFlat(true);
//TODO    tqInstallMsgHandler( oldHandler );

//(js)    d->pathCombo = new KURLComboBox( KURLComboBox::Directories, true,
//(js)                                     toolbar, "path combo" );
//(js)    TQToolTip::add( d->pathCombo, i18n("Often used directories") );
//(js)    TQWhatsThis::add( d->pathCombo, "<qt>" + i18n("Commonly used locations are listed here. "
//(js)                                                 "This includes standard locations, such as your home directory, as well as "
//(js)                                                 "locations that have been visited recently.") + autocompletionWhatsThisText);
/*
    KURL u;
    u.setPath( TQDir::rootDirPath() );
    TQString text = i18n("Root Directory: %1").arg( u.path() );
    d->pathCombo->addDefaultURL( u,
                                 KMimeType::pixmapForURL( u, 0, TDEIcon::Small ),
                                 text );

    u.setPath( TQDir::homeDirPath() );
    text = i18n("Home Directory: %1").arg( u.path( +1 ) );
    d->pathCombo->addDefaultURL( u, KMimeType::pixmapForURL( u, 0, TDEIcon::Small ),
                                 text );

    KURL docPath;
    docPath.setPath( TDEGlobalSettings::documentPath() );
    if ( u.path(+1) != docPath.path(+1) ) {
        text = i18n("Documents: %1").arg( docPath.path( +1 ) );
        d->pathCombo->addDefaultURL( u,
                                     KMimeType::pixmapForURL( u, 0, TDEIcon::Small ),
                                     text );
    }

    u.setPath( TDEGlobalSettings::desktopPath() );
    text = i18n("Desktop: %1").arg( u.path( +1 ) );
    d->pathCombo->addDefaultURL( u,
                                 KMimeType::pixmapForURL( u, 0, TDEIcon::Small ),
                                 text );

    u.setPath( "/tmp" );

    d->url = getStartURL( startDir, d->fileClass );
    d->selection = d->url.url();

    // If local, check it exists. If not, go up until it exists.
    if ( d->url.isLocalFile() )
    {
        if ( !TQFile::exists( d->url.path() ) )
        {
            d->url = d->url.upURL();
            TQDir dir( d->url.path() );
            while ( !dir.exists() )
            {
                d->url = d->url.upURL();
                dir.setPath( d->url.path() );
            }
        }
    }

    ops = new KDirOperator(d->url, d->mainWidget, "KFileDialog::ops");
    ops->setOnlyDoubleClickSelectsFiles( true );
    connect(ops, TQT_SIGNAL(urlEntered(const KURL&)),
            TQT_SLOT(urlEntered(const KURL&)));
    connect(ops, TQT_SIGNAL(fileHighlighted(const KFileItem *)),
            TQT_SLOT(fileHighlighted(const KFileItem *)));
    connect(ops, TQT_SIGNAL(fileSelected(const KFileItem *)),
            TQT_SLOT(fileSelected(const KFileItem *)));
    connect(ops, TQT_SIGNAL(finishedLoading()),
            TQT_SLOT(slotLoadingFinished()));

    ops->setupMenu(KDirOperator::SortActions |
                   KDirOperator::FileActions |
                   KDirOperator::ViewActions);
    TDEActionCollection *coll = ops->actionCollection();

    // plug nav items into the toolbar
    coll->action( "up" )->plug( toolbar );
    coll->action( "up" )->setWhatsThis(i18n("<qt>Click this button to enter the parent directory.<p>"
                                            "For instance, if the current location is file:/home/%1 clicking this "
                                            "button will take you to file:/home.</qt>").arg(getlogin()));
    coll->action( "back" )->plug( toolbar );
    coll->action( "back" )->setWhatsThis(i18n("Click this button to move backwards one step in the browsing history."));
    coll->action( "forward" )->plug( toolbar );
    coll->action( "forward" )->setWhatsThis(i18n("Click this button to move forward one step in the browsing history."));
    coll->action( "reload" )->plug( toolbar );
    coll->action( "reload" )->setWhatsThis(i18n("Click this button to reload the contents of the current location."));
    coll->action( "mkdir" )->setShortcut(Key_F10);
    coll->action( "mkdir" )->plug( toolbar );
    coll->action( "mkdir" )->setWhatsThis(i18n("Click this button to create a new directory."));

    d->bookmarkHandler = new KFileBookmarkHandler( this );
    toolbar->insertButton(TQString::fromLatin1("bookmark"),
                          (int)HOTLIST_BUTTON, true,
                          i18n("Bookmarks"));
    toolbar->getButton(HOTLIST_BUTTON)->setPopup( d->bookmarkHandler->menu(),
                                                  true);
    TQWhatsThis::add(toolbar->getButton(HOTLIST_BUTTON),
                    i18n("<qt>This button allows you to bookmark specific locations. "
                         "Click on this button to open the bookmark menu where you may add, "
                         "edit or select a bookmark.<p>"
                         "These bookmarks are specific to the file dialog, but otherwise operate "
                         "like bookmarks elsewhere in TDE.</qt>"));
    connect( d->bookmarkHandler, TQT_SIGNAL( openURL( const TQString& )),
             TQT_SLOT( enterURL( const TQString& )));

    TDEToggleAction *showSidebarAction =
        new TDEToggleAction(i18n("Show Quick Access Navigation Panel"), Key_F9, coll,"toggleSpeedbar");
    connect( showSidebarAction, TQT_SIGNAL( toggled( bool ) ),
             TQT_SLOT( toggleSpeedbar( bool )) );

    TDEActionMenu *menu = new TDEActionMenu( i18n("Configure"), "configure", this, "extra menu" );
    menu->setWhatsThis(i18n("<qt>This is the configuration menu for the file dialog. "
                            "Various options can be accessed from this menu including: <ul>"
                            "<li>how files are sorted in the list</li>"
                            "<li>types of view, including icon and list</li>"
                            "<li>showing of hidden files</li>"
                            "<li>the Quick Access navigation panel</li>"
                            "<li>file previews</li>"
                            "<li>separating directories from files</li></ul></qt>"));
    menu->insert( coll->action( "sorting menu" ));
    menu->insert( coll->action( "separator" ));
    coll->action( "short view" )->setShortcut(Key_F6);
    menu->insert( coll->action( "short view" ));
    coll->action( "detailed view" )->setShortcut(Key_F7);
    menu->insert( coll->action( "detailed view" ));
    menu->insert( coll->action( "separator" ));
    coll->action( "show hidden" )->setShortcut(Key_F8);
    menu->insert( coll->action( "show hidden" ));
    menu->insert( showSidebarAction );
    coll->action( "preview" )->setShortcut(Key_F11);
    menu->insert( coll->action( "preview" ));
    coll->action( "separate dirs" )->setShortcut(Key_F12);
    menu->insert( coll->action( "separate dirs" ));

    menu->setDelayed( false );
    connect( menu->popupMenu(), TQT_SIGNAL( aboutToShow() ),
             ops, TQT_SLOT( updateSelectionDependentActions() ));
    menu->plug( toolbar );
*/
    /*
     * ugly little hack to have a 5 pixel space between the buttons
     * and the combo box
     */
/*    TQWidget *spacerWidget = new TQWidget(toolbar);
//(js)    spacerWidget->setMinimumWidth(spacingHint());
//(js)    spacerWidget->setMaximumWidth(spacingHint());
    d->m_pathComboIndex = toolbar->insertWidget(-1, -1, spacerWidget);
    toolbar->insertWidget(PATH_COMBO, 0, d->pathCombo);


    toolbar->setItemAutoSized (PATH_COMBO);
    toolbar->setIconText(TDEToolBar::IconOnly);
    toolbar->setBarPos(TDEToolBar::Top);
    toolbar->setMovingEnabled(false);
    toolbar->adjustSize();

    d->pathCombo->setCompletionObject( ops->dirCompletionObject(), false );

    connect( d->pathCombo, TQT_SIGNAL( urlActivated( const KURL&  )),
             this,  TQT_SLOT( enterURL( const KURL& ) ));
    connect( d->pathCombo, TQT_SIGNAL( returnPressed( const TQString&  )),
             this,  TQT_SLOT( enterURL( const TQString& ) ));
    connect( d->pathCombo, TQT_SIGNAL(textChanged( const TQString& )),
             TQT_SLOT( pathComboChanged( const TQString& ) ));
    connect( d->pathCombo, TQT_SIGNAL( completion( const TQString& )),
             TQT_SLOT( dirCompletion( const TQString& )));
    connect( d->pathCombo, TQT_SIGNAL( textRotation(TDECompletionBase::KeyBindingType) ),
             d->pathCombo, TQT_SLOT( rotateText(TDECompletionBase::KeyBindingType) ));

    TQString whatsThisText;

    // the Location label/edit
    d->locationLabel = new TQLabel(i18n("&Location:"), d->mainWidget);
    locationEdit = new KURLComboBox(KURLComboBox::Files, true,
                                    d->mainWidget, "LocationEdit");
    updateLocationWhatsThis ();
    d->locationLabel->setBuddy(locationEdit);

    // to get the completionbox-signals connected:
    locationEdit->setHandleSignals( true );
    (void) locationEdit->completionBox();

    locationEdit->setFocus();
//     locationEdit->setCompletionObject( new KURLCompletion() );
//     locationEdit->setAutoDeleteCompletionObject( true );
    locationEdit->setCompletionObject( ops->completionObject(), false );

    connect( locationEdit, TQT_SIGNAL( returnPressed() ),
             this, TQT_SLOT( slotOk()));
    connect(locationEdit, TQT_SIGNAL( activated( const TQString&  )),
            this,  TQT_SLOT( locationActivated( const TQString& ) ));
    connect( locationEdit, TQT_SIGNAL( completion( const TQString& )),
             TQT_SLOT( fileCompletion( const TQString& )));
    connect( locationEdit, TQT_SIGNAL( textRotation(TDECompletionBase::KeyBindingType) ),
             locationEdit, TQT_SLOT( rotateText(TDECompletionBase::KeyBindingType) ));

    // the Filter label/edit
    whatsThisText = i18n("<qt>This is the filter to apply to the file list. "
                         "File names that do not match the filter will not be shown.<p>"
                         "You may select from one of the preset filters in the "
                         "drop down menu, or you may enter a custom filter "
                         "directly into the text area.<p>"
                         "Wildcards such as * and ? are allowed.</qt>");
    d->filterLabel = new TQLabel(i18n("&Filter:"), d->mainWidget);
    TQWhatsThis::add(d->filterLabel, whatsThisText);
    filterWidget = new KFileFilterCombo(d->mainWidget,
                                        "KFileDialog::filterwidget");
    TQWhatsThis::add(filterWidget, whatsThisText);
    setFilter(filter);
    d->filterLabel->setBuddy(filterWidget);
    connect(filterWidget, TQT_SIGNAL(filterChanged()), TQT_SLOT(slotFilterChanged()));

    // the Automatically Select Extension checkbox
    // (the text, visibility etc. is set in updateAutoSelectExtension(), which is called by readConfig())
    d->autoSelectExtCheckBox = new TQCheckBox (d->mainWidget);
    connect(d->autoSelectExtCheckBox, TQT_SIGNAL(clicked()), TQT_SLOT(slotAutoSelectExtClicked()));

    initGUI(); // activate GM

    readRecentFiles( config );

    adjustSize();

    // we set the completionLock to avoid entering pathComboChanged() when
    // inserting the list of URLs into the combo.
    d->completionLock = true;
    ops->setViewConfig( config, ConfigGroup );
    readConfig( config, ConfigGroup );
    setSelection(d->selection);
    d->completionLock = false;
	*/
}

void KexiStartupFileDialogBase::clearFilter()
{
	d->kde_filters = "";//(js)
	TQFileDialog::setFilter(""); //(js);
//todo    d->mimetypes.clear();
//todo    d->hasDefaultFilter = false;

	updateAutoSelectExtension ();
}

KFile::Mode KexiStartupFileDialogBase::mode() const
{
	return d->mode;
}

void KexiStartupFileDialogBase::setMode( KFile::Mode m )
{
    //(js) translate mode for TQFileDialog
    d->mode = m;
    TQFileDialog::Mode qm = (TQFileDialog::Mode)0;
    if (m & KFile::File) qm = Mode(qm | TQFileDialog::AnyFile);
    else if (m & KFile::Directory) qm = Mode(qm | TQFileDialog::DirectoryOnly);
    if (m & KFile::Files) qm = Mode(qm | TQFileDialog::ExistingFiles);
    if (m & KFile::ExistingOnly) qm = Mode(qm | TQFileDialog::ExistingFile);
    
    TQFileDialog::setMode( qm );
/*(js)    ops->setMode(m);
    if ( ops->dirOnlyMode() ) {
//(js)        filterWidget->setDefaultFilter( i18n("*|All Directories") );
    }
    else {
//(js)        filterWidget->setDefaultFilter( i18n("*|All Files") );
    }

    updateAutoSelectExtension ();*/
}

void KexiStartupFileDialogBase::setMode( unsigned int m )
{
    setMode(static_cast<KFile::Mode>( m ));
}

void KexiStartupFileDialogBase::setOperationMode( KFileDialog::OperationMode mode )
{
//    d->operationMode = mode;
  //  d->keepLocation = (mode == Saving);
    if (mode == KFileDialog::Saving) {
      setMode( KFile::File );
      setIcon( TDEGlobal::iconLoader()->loadIcon("filesave", TDEIcon::Desktop) );
    }
//(js)    filterWidget->setEditable( !d->hasDefaultFilter || mode != Saving );
//(js)    d->okButton->setGuiItem( (mode == Saving) ? KStdGuiItem::save() : KStdGuiItem::ok() );
//TODO    updateLocationWhatsThis ();
    updateAutoSelectExtension ();
}

TQString KexiStartupFileDialogBase::currentFilter() const
{
	//(js)filterWidget->currentFilter();

	//we need to convert TQt filter format to TDE format
	//TQt format: "some text (*.first *.second)" or "All (*)"
	//TDE format: "*.first *.second" or "*"
	TQString f = selectedFilter();
	if (f.find('(')!=-1)
		f = f.mid(f.find('(')+1);
	if (f.mid(f.find(')')!=-1))
		f = f.left(f.find(')'));
	return f;
}

void KexiStartupFileDialogBase::setFilter(const TQString& filter)
{
	d->kde_filters = filter;
    int pos = d->kde_filters.find('/');

	// Check for an un-escaped '/', if found
    // interpret as a MIME filter.

    if (pos > 0 && filter[pos - 1] != '\\') {
        TQStringList filters = TQStringList::split( " ", d->kde_filters );
        setMimeFilter( filters );
        return;
    }
	TQFileDialog::setFilters( convertKFileDialogFilterToTQFileDialogFilter(filter) );
	//</js>
//(js)    ops->clearFilter();
//(js)    filterWidget->setFilter(copy);
//(js)    ops->setNameFilter(filterWidget->currentFilter());
//(js)    d->hasDefaultFilter = false;
//(js)    filterWidget->setEditable( true );

    updateAutoSelectExtension ();
}

void KexiStartupFileDialogBase::setMimeFilter( const TQStringList& mimeTypes,
                                 const TQString& defaultType )
{
    d->mimetypes = mimeTypes;
//(js)    filterWidget->setMimeFilter( mimeTypes, defaultType );

//(js)    TQStringList types = TQStringList::split(" ", filterWidget->currentFilter());
//(js)    types.append( TQString::fromLatin1( "inode/directory" ));
//(js)    ops->clearFilter();
//(js)    ops->setMimeFilter( types );
//(js)    d->hasDefaultFilter = !defaultType.isEmpty();
//(js)    filterWidget->setEditable( !d->hasDefaultFilter ||
//(js)                               d->operationMode != Saving );

//TODO    updateAutoSelectExtension ();
}

TQString KexiStartupFileDialogBase::realStartDir(const TQString& startDir)
{
	if (!startDir.startsWith(":"))
		return startDir;
	TQString recentDir; //dummy
	TQString path( KFileDialog::getStartURL(startDir, recentDir).path() );
	if (path.isEmpty())
		return TQString();
	TQFileInfo fi(path);
	return fi.isDir() ? fi.absFilePath() : fi.dir(true).absPath();
}

void KexiStartupFileDialogBase::saveLastVisitedPath(const TQString& path)
{
	if (!m_lastVisitedPathsVariable.isEmpty()) {
		//save last visited dir path
//		TQString dir = TQDir(path).absPath();
		TQFileInfo fi(path);
		TQString dir( fi.isDir() ? fi.absFilePath() : fi.dir(true).absPath() );
		if (!dir.isEmpty())
			TDERecentDirs::add(m_lastVisitedPathsVariable, dir);
	}
}
