/***************************************************************************
*   Copyright (C) 2001 by Daniel Engelschalt                              *
*   daniel.engelschalt@gmx.net                                            *
*   Copyright (C) 2004 Jonas Jacobi<j.jacobi@gmx.de>                      *
*                                                                         *
*   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 <tqtabwidget.h>
#include <tqbuttongroup.h>
#include <tqcheckbox.h>
#include <tqlineedit.h>
#include <tqspinbox.h>
#include <tqradiobutton.h>
#include <tqcombobox.h>
#include <tqmultilineedit.h>
#include <tqslider.h>
#include <tqheader.h>
#include <tqcolor.h>
#include <tqlabel.h>
#include <tqlayout.h>

// kde includes
#include <kdevproject.h>
#include <tdefiledialog.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <tdefileitem.h>
#include <kurlrequester.h>
#include <keditlistbox.h>
#include <tdelistview.h>
#include <knuminput.h>
#include <tdemainwindow.h>
#include <klineedit.h>
#include <tdeversion.h>
// tdevelop includes
#include <domutil.h>
#include <kdevcoderepository.h>
#include <kdevmainwindow.h>
#include <kdevcoderepository.h>
#include <catalog.h>
// std includes
#include <stdlib.h>

#include "cppsupportfactory.h"
#include "ccconfigwidget.h"
#include "qtbuildconfig.h"
#include "cppsupportpart.h"
#include "cppcodecompletionconfig.h"
#include "cppsplitheadersourceconfig.h"
#include "createpcsdialog.h"
#include "creategettersetterconfiguration.h"

using namespace std;


CCConfigWidget::CCConfigWidget( CppSupportPart* part, TQWidget* parent, const char* name )
		: CCConfigWidgetBase( parent, name )
{
	m_pPart = part;
	connect( m_pPart->codeRepository(), TQ_SIGNAL( catalogRegistered( Catalog* ) ),
	         this, TQ_SLOT( catalogRegistered( Catalog* ) ) );
	connect( m_pPart->codeRepository(), TQ_SIGNAL( catalogUnregistered( Catalog* ) ),
	         this, TQ_SLOT( catalogUnregistered( Catalog* ) ) );

	connect( m_qtDir, TQ_SIGNAL(urlSelected(const TQString &)),
		 this, TQ_SLOT(isValidTQtDir(const TQString &)));
	connect( m_qtDir, TQ_SIGNAL(textChanged(const TQString &)),
		 this, TQ_SLOT(isValidTQtDir(const TQString &)));

	initGeneralTab( );
	initTQtTab();
	initCodeCompletionTab( );
	initGetterSetterTab( );
	initSplitTab();
	inputCodeCompletion->setRange( 0, 2000, 100, false );
	inputArgumentsHint->setRange( 0, 2000, 100, false );
}

void CCConfigWidget::initGeneralTab( )
{
	TQDomDocument dom = *m_pPart->projectDom();
	interface_suffix->setText( DomUtil::readEntry( dom, "/cppsupportpart/filetemplates/interfacesuffix", ".h" ) );
	implementation_suffix->setText( DomUtil::readEntry( dom, "/cppsupportpart/filetemplates/implementationsuffix", ".cpp" ) );

	TDEConfig *config = CppSupportFactory::instance() ->config();
	if ( config )
	{
		config->setGroup( "General" );
		m_switchShouldMatch->setChecked( config->readBoolEntry( "SwitchShouldMatch", true ) );
		m_showContextMenuExplosion->setChecked( config->readBoolEntry( "ShowContextMenuExplosion", false ) );
	}
}

CCConfigWidget::~CCConfigWidget( )
{}

void CCConfigWidget::accept( )
{
	saveFileTemplatesTab();
	saveTQtTab();
	saveCodeCompletionTab();
	saveGetterSetterTab();
	saveSplitTab();
}

void CCConfigWidget::saveFileTemplatesTab( )
{
	TQDomDocument dom = *m_pPart->projectDom();
	DomUtil::writeEntry( dom, "/cppsupportpart/filetemplates/interfacesuffix", interface_suffix->text() );
	DomUtil::writeEntry( dom, "/cppsupportpart/filetemplates/implementationsuffix", implementation_suffix->text() );

	TDEConfig *config = CppSupportFactory::instance() ->config();
	if ( config )
	{
		config->setGroup( "General" );
		config->writeEntry( "SwitchShouldMatch", m_switchShouldMatch->isChecked() );
		config->writeEntry( "ShowContextMenuExplosion", m_showContextMenuExplosion->isChecked() );
	}
}

void CCConfigWidget::initCodeCompletionTab( )
{
	advancedOptions->header() ->hide();

	CppCodeCompletionConfig* c = m_pPart->codeCompletionConfig();

	inputCodeCompletion->setValue( c->codeCompletionDelay() );
	inputArgumentsHint->setValue( c->argumentsHintDelay() );
	checkAutomaticCodeCompletion->setChecked( c->automaticCodeCompletion() );
	checkAutomaticArgumentsHint->setChecked( c->automaticArgumentsHint() );

	checkCompleteArgumentType->setChecked( c->processFunctionArguments() );
	checkCompleteReturnType->setChecked( c->processPrimaryTypes() );
	//checkShowOnlyAccessible->setChecked( c->showOnlyAccessibleItems() );

	editNamespaceAlias->setText( c->namespaceAliases() );
	checkBox18->setChecked( c->showEvaluationContextMenu() );
	checkShowTypeEvaluationInStatusBar->setChecked( c->statusBarTypeEvaluation() );
	checkShowCommentInArgumentHint->setChecked( c->showCommentWithArgumentHint() );
	/*
	switch( c->completionBoxItemOrder() ) {
	case CppCodeCompletionConfig::ByAccessLevel:
		radioGroupByAccess->setChecked( true );
		break;
	case CppCodeCompletionConfig::ByClass:
		radioGroupByClass->setChecked( true );
		break;
	case CppCodeCompletionConfig::ByAlphabet:
		radioGroupByAlphabet->setChecked( true );
		break;
	}*/

	TQValueList<Catalog*> catalogs = m_pPart->codeRepository() ->registeredCatalogs();
	for ( TQValueList<Catalog*>::Iterator it = catalogs.begin(); it != catalogs.end(); ++it )
	{
		Catalog* c = *it;
		TQFileInfo dbInfo( c->dbName() );
		TQCheckListItem* item = new TQCheckListItem( advancedOptions, KURL::decode_string( dbInfo.baseName(true) ), TQCheckListItem::CheckBox );
		item->setOn( c->enabled() );

		m_catalogs[ item ] = c;
	}

	checkPreprocessIncludedHeaders->setChecked( c->preProcessAllHeaders() && !c->parseMissingHeaders() );
	checkParseMissingHeaders->setChecked( c->parseMissingHeaders() );
	checkListGlobalItems->setChecked( c->alwaysIncludeNamespaces() );
	checkResolveIncludePaths->setChecked( c->resolveIncludePaths() );
	editIncludePaths->setText( c->customIncludePaths() );
}

void CCConfigWidget::saveCodeCompletionTab( )
{
	CppCodeCompletionConfig * c = m_pPart->codeCompletionConfig();

	c->setCodeCompletionDelay( inputCodeCompletion->value() );
	c->setArgumentsHintDelay( inputArgumentsHint->value() );

	c->setAutomaticCodeCompletion( checkAutomaticCodeCompletion->isChecked() );
	c->setAutomaticArgumentsHint( checkAutomaticArgumentsHint->isChecked() );

	c->setProcessFunctionArguments( checkCompleteArgumentType->isChecked() );
	c->setProcessPrimaryTypes( checkCompleteReturnType->isChecked() );
	//c->setShowOnlyAccessibleItems( checkShowOnlyAccessible->isChecked() );

	c->setNamespaceAliases( editNamespaceAlias->text() );
	c->setShowEvaluationContextMenu( checkBox18->isChecked() );
	c->setStatusBarTypeEvaluation( checkShowTypeEvaluationInStatusBar->isChecked() );
	c->setShowCommentWithArgumentHint( checkShowCommentInArgumentHint->isChecked() );

	/*if( radioGroupByAccess->isChecked() )
		c->setCompletionBoxItemOrder( CppCodeCompletionConfig::ByAccessLevel );

	if( radioGroupByClass->isChecked() )
		c->setCompletionBoxItemOrder( CppCodeCompletionConfig::ByClass );

	if( radioGroupByAlphabet->isChecked() )
		c->setCompletionBoxItemOrder( CppCodeCompletionConfig::ByAlphabet );*/

	for ( TQMap<TQCheckListItem*, Catalog*>::Iterator it = m_catalogs.begin(); it != m_catalogs.end(); ++it )
	{
		it.data() ->setEnabled( it.key() ->isOn() );
	}

	c->setPreProcessAllHeaders( checkPreprocessIncludedHeaders->isChecked() || checkParseMissingHeaders->isChecked() );
	c->setParseMissingHeaders( checkParseMissingHeaders->isChecked() );
	c->setAlwaysIncludeNamespaces( checkListGlobalItems->isChecked() );
	c->setResolveIncludePaths( checkResolveIncludePaths->isChecked() );
	c->setCustomIncludePaths( editIncludePaths->text() );

	c->store();
}

void CCConfigWidget::slotNewPCS( )
{
	CreatePCSDialog dlg( m_pPart, m_pPart->mainWindow() ->main() );
	dlg.importerListView->setFocus();
	dlg.exec();
}

void CCConfigWidget::slotRemovePCS()
{
	if ( !advancedOptions->selectedItem() )
		return ;

	TQString db = advancedOptions->selectedItem() ->text( 0 );
	TQString question = i18n( "Are you sure you want to delete the \"%1\" database?" ).arg( db );

	TDEStandardDirs *dirs = m_pPart->instance() ->dirs();
	TQString dbName = dirs->saveLocation( "data", "kdevcppsupport/pcs" ) + KURL::encode_string_no_slash( db ) + ".db";

	if ( KMessageBox::Continue == KMessageBox::warningContinueCancel( 0, question, i18n( "Delete Database" ), KStdGuiItem::del() ) )
	{
		m_pPart->removeCatalog( dbName );
	}
}

void CCConfigWidget::catalogRegistered( Catalog * c )
{
	TQFileInfo dbInfo( c->dbName() );
	TQCheckListItem* item = new TQCheckListItem( advancedOptions, KURL::decode_string( dbInfo.baseName(true) ), TQCheckListItem::CheckBox );
	item->setOn( c->enabled() );

	m_catalogs[ item ] = c;
}

void CCConfigWidget::catalogUnregistered( Catalog * c )
{
	for ( TQMap<TQCheckListItem*, Catalog*>::Iterator it = m_catalogs.begin(); it != m_catalogs.end(); ++it )
	{
		if ( it.data() == c )
		{
			TQCheckListItem * item = it.key();
			delete( item );
			m_catalogs.remove( it );
			break;
		}
	}
}

void CCConfigWidget::initGetterSetterTab( )
{
	CreateGetterSetterConfiguration * config = m_pPart->createGetterSetterConfiguration();

	if ( config == 0 )
		return ;

	m_edtGet->setText( config->prefixGet() );
	m_edtSet->setText( config->prefixSet() );
	m_edtRemovePrefix->setText( config->prefixVariable().join( "," ) );
	m_edtParameterName->setText( config->parameterName() );

	slotGetterSetterValuesChanged();
}

void CCConfigWidget::slotGetterSetterValuesChanged( )
{
	bool hasError = false;
	if ( m_edtParameterName->text().isEmpty() )
	{
		m_lblParameterName->setPaletteForegroundColor( TQColor( "red" ) );
		m_edtExampleGet->setText( "error, missing parametername" );
		m_edtExampleSet->setText( "error, missing parametername" );
		hasError = true;
	}

	TQString name = m_edtVariableName->text();
	if ( name.isEmpty() )
	{
		m_lblVariableName->setPaletteForegroundColor( TQColor( "red" ) );
		m_edtExampleGet->setText( "error, missing variablename" );
		m_edtExampleSet->setText( "error, missing variablename" );
		hasError = true;
	}

	if ( hasError )
	{
		m_edtExampleGet->setPaletteForegroundColor( TQColor( "red" ) );
		m_edtExampleSet->setPaletteForegroundColor( TQColor( "red" ) );

		return ;
	}
	else
	{
		m_lblVariableName->setPaletteForegroundColor( TQColor( "black" ) );
		m_lblParameterName->setPaletteForegroundColor( TQColor( "black" ) );
		m_edtExampleGet->setPaletteForegroundColor( TQColor( "black" ) );
		m_edtExampleSet->setPaletteForegroundColor( TQColor( "black" ) );
	}

	TQStringList prefixes = TQStringList::split( ",", m_edtRemovePrefix->text().replace( " ", "" ) );
	unsigned int len = 0;
	TQStringList::ConstIterator theend = prefixes.end();
	for ( TQStringList::ConstIterator ci = prefixes.begin(); ci != theend; ++ci )
	{
		if ( name.startsWith( *ci ) && ( *ci ).length() > len )
			len = ( *ci ).length();
	}

	if ( len > 0 )
		name.remove( 0, len );

	TQString getName = name;
	if ( !m_edtGet->text().isEmpty() )
	{
		getName[ 0 ] = getName[ 0 ].upper();
		getName.prepend( m_edtGet->text() );
	}

	TQString setName = name;
	if ( !m_edtSet->text().isEmpty() )
	{
		setName[ 0 ] = setName[ 0 ].upper();
		setName.prepend( m_edtSet->text() );
	}

	m_edtExampleGet->setText( "string " + getName + "() const;" );
	m_edtExampleSet->setText( "void " + setName + "(const string& " + m_edtParameterName->text() + ");" );
}

void CCConfigWidget::saveGetterSetterTab( )
{
	if ( m_edtParameterName->text().isEmpty() || m_edtGet->text() == m_edtSet->text() )
		return ;

	CreateGetterSetterConfiguration* config = m_pPart->createGetterSetterConfiguration();
	if ( config == 0 )
		return ;

	config->setPrefixGet( m_edtGet->text() );
	config->setPrefixSet( m_edtSet->text() );
	config->setPrefixVariable( TQStringList::split( ",", m_edtRemovePrefix->text().replace( " ", "" ) ) );
	config->setParameterName( m_edtParameterName->text() );
	config->store();
}

void CCConfigWidget::initSplitTab( )
{
	CppSplitHeaderSourceConfig * config = m_pPart->splitHeaderSourceConfig();

	if ( config == 0 )
		return ;

	m_splitEnable->setChecked( config->splitEnabled() );
	m_splitSync->setChecked( config->autoSync() );

	TQString o = config->orientation();
	m_splitVertical->setChecked( o == "Vertical" );
	m_splitHorizontal->setChecked( o == "Horizontal" );
}

void CCConfigWidget::saveSplitTab( )
{
	CppSplitHeaderSourceConfig * config = m_pPart->splitHeaderSourceConfig();

	if ( config == 0 )
		return ;

	config->setSplitEnable( m_splitEnable->isChecked() );
	config->setAutoSync( m_splitSync->isChecked() );

	if ( m_splitVertical->isChecked() )
		config->setOrientation( "Vertical" );
	else if ( m_splitHorizontal->isChecked() )
		config->setOrientation( "Horizontal" );

	config->store();
}

void CCConfigWidget::initTQtTab()
{
	m_qtDir->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly);

	QtBuildConfig* c = m_pPart->qtBuildConfig();
	c->init();

	m_qtUsed->setChecked( c->isUsed() );
	m_versionQt3->setChecked( true );
	m_kdevembedded->setEnabled( true );
	m_kdevexternal->setEnabled( true );
	m_designerPath->setEnabled( true );
	m_qmakePath->setEnabled( true );
	m_qtDir->setEnabled( true );
	m_txtQtDir->setEnabled( true );
	m_txtDesigner->setEnabled( true );
	m_qtStyleVersion3->setChecked( true );
	m_qtDir->setURL( c->root() );
	isValidTQtDir(m_qtDir->url());
    m_qmakePath->setURL( c->qmakePath() );
    isExecutable( m_qmakePath->url() );
    m_designerPath->setURL( c->designerPath() );
    isExecutable( m_designerPath->url() );
	if ( c->designerIntegration() == "EmbeddedKDevDesigner" )
	{
		m_kdevembedded->setChecked( true );
	}
	else if ( c->designerIntegration() == "ExternalKDevDesigner" )
	{
		m_kdevexternal->setChecked( true );
	}else
	{
		m_tqtdesigner->setChecked( true );
	}
}

bool CCConfigWidget::isExecutable( const TQString& path )
{
    TQFileInfo fi(path);

    return ( fi.exists() && fi.isExecutable()  );
}

void CCConfigWidget::isTQMakeExecutable( const TQString& path )
{
    if( !isExecutable( path ) )
    {
        m_qmakePath->lineEdit()->setPaletteForegroundColor(TQColor("#ff0000"));
    }else
    {
        m_qmakePath->lineEdit()->unsetPalette();
    }
}

void CCConfigWidget::isDesignerExecutable( const TQString& path )
{
    if( !isExecutable( path ) )
    {
        m_designerPath->lineEdit()->setPaletteForegroundColor(TQColor("#ff0000"));
    }else
    {
        m_designerPath->lineEdit()->unsetPalette();
    }
}

void CCConfigWidget::saveTQtTab()
{
	QtBuildConfig* c = m_pPart->qtBuildConfig();

	c->setUsed( m_qtUsed->isChecked() );
	c->setVersion( 3 );
	c->setIncludeStyle( 3 );
	c->setRoot( m_qtDir->url() );
    c->setTQMakePath( m_qmakePath->url() );
    c->setDesignerPath( m_designerPath->url() );
	if( m_kdevembedded->isChecked() )
	{
		c->setDesignerIntegration( "EmbeddedKDevDesigner" );
	}
	else if ( m_kdevexternal->isChecked() )
	{
		c->setDesignerIntegration( "ExternalKDevDesigner" );
	}else
	{
		c->setDesignerIntegration( "ExternalDesigner" );
	}
	c->store();
}

void CCConfigWidget::isValidTQtDir( const TQString &dir )
{
	TQFileInfo inc( dir + TQString( TQChar( TQDir::separator() ) )+
			"include"+TQString( TQChar( TQDir::separator() ) )+
			"tqt.h" );
	m_qtDir->lineEdit()->unsetPalette();
}

void CCConfigWidget::toggleTQtVersion( bool )
{
  if ( m_versionQt3->isChecked() )
  {
    m_qtStyleVersion3->setChecked( true );
    m_kdevembedded->setEnabled( true );
    m_kdevexternal->setEnabled( true );
  }
  isValidTQtDir( m_qtDir->url() );
  isTQMakeExecutable( m_qmakePath->url() );
  isDesignerExecutable( m_designerPath->url() );
}

void CCConfigWidget::openPluginPaths()
{
    kdDebug(9024) << "Plugin paths opened" << endl;
    QtBuildConfig* c = m_pPart->qtBuildConfig();
    KDialog d( this );
    TQVBoxLayout* mainlayout = new TQVBoxLayout( &d );
    KPushButton* ok = new KPushButton( KStdGuiItem::ok(), &d );
    connect( ok, TQ_SIGNAL(clicked()), &d, TQ_SLOT(accept()));
    KPushButton* cancel = new KPushButton( KStdGuiItem::cancel(), &d );
    connect( cancel, TQ_SIGNAL(clicked()), &d, TQ_SLOT(reject()));
    TQHBoxLayout* btns = new TQHBoxLayout( &d );
    btns->addItem( new TQSpacerItem(10,10,TQSizePolicy::Expanding) );
    btns->addWidget(ok);
    btns->addWidget(cancel);

    d.setCaption( i18n( "Edit TQt Designer Plugin Paths" ) );
    KURLRequester * req = new KURLRequester( &d );
    req->setMode( KFile::Directory );
    KEditListBox* p = new KEditListBox( i18n( "Plugin Paths" ), req->customEditor(), &d );
    p->insertStringList( c->designerPluginPaths() );
    mainlayout->addWidget( p );
    mainlayout->addLayout( btns );
    d.resize( 450, 250 );
    if( d.exec() == TQDialog::Accepted)
    {
        c->setDesignerPluginPaths( p->items() );
    }
}

#include "ccconfigwidget.moc"
