/* ****************************************************************************
  This file is part of KBabel

  Copyright (C) 2002-2005  by Stanislav Visnovsky
                            <visnovsky@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.

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt. If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
      
**************************************************************************** */
#include "context.h"
#include "klisteditor.h"

#include <qcombobox.h>
#include <qfileinfo.h>
#include <qframe.h>
#include <qhbox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qlistbox.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qvgroupbox.h>

#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kmessagebox.h>

#include <klibloader.h>
#include <ktrader.h>
#include <ktexteditor/document.h>
#include <ktexteditor/editinterface.h>
#include <ktexteditor/selectioninterface.h>
#include <ktexteditor/viewcursorinterface.h>

SourceContext::SourceContext(QWidget *parent, KBabel::Project::Ptr project): QWidget(parent)
    , _part(0)
    , _view(0)
    , _referenceCombo(0)
    , _layout(0)
    , _project(project)
{
    _referenceList.clear();
    _referenceCombo = new QComboBox( this );
    connect( _referenceCombo, SIGNAL(activated(int)), this, SLOT(updateToSelected(int)));
    
    _layout= new QVBoxLayout(this);
    _layout->addWidget(_referenceCombo);
}

void SourceContext::setContext(const QString& packageDir, const QString& packageName, const QString& gettextComment)
{
    if( !_part && !loadPart() ) return;
    _referenceCombo->clear();
    _referenceList.clear();
    _referenceList = resolvePath(packageDir,packageName,gettextComment);
    
    for( QValueList<ContextInfo>::Iterator it=_referenceList.begin(); it!=_referenceList.end() ; ++it)
	_referenceCombo->insertItem((*it).path);
    _referenceCombo->setEnabled( !_referenceList.isEmpty() );
    
    if( _referenceList.isEmpty() )
    {
	(dynamic_cast<KTextEditor::EditInterface *>(_part))->setText(i18n("Corresponding source file not found"));
	_part->setReadWrite(false);
	_part->setModified(false);
    } 
    else 
    {
	_referenceCombo->setCurrentItem(0);
	updateToSelected(0);
    }
}

void SourceContext::updateToSelected(int index)
{
    if( !_part ) return;
    ContextInfo ci = *(_referenceList.at(index));
    if( _part->url() != KURL(ci.path) )
    {
	_part->openURL( KURL(ci.path) );
    }
    _part->setReadWrite(true);
    (dynamic_cast<KTextEditor::ViewCursorInterface *>(_view))->setCursorPosition(ci.line,0);
    (dynamic_cast<KTextEditor::SelectionInterface *>(_part))->setSelection(ci.line-1,0,ci.line,0);
}

QValueList<ContextInfo> SourceContext::resolvePath(const QString& packageDir, const QString& packageName, const QString& gettextComment)
{
    QStringList prefixes;
    QStringList paths = _project->settings()->paths();
    
    for( QStringList::Iterator it = paths.begin() 
	; it!=paths.end() ; ++it)
    {
	QString pref = (*it);
        pref.replace( "@PACKAGEDIR@", packageDir);
        pref.replace( "@PACKAGE@", packageName);
	pref.replace( "@CODEROOT@", _project->settings()->codeRoot());
	prefixes.append(pref);
    }

    QStringList references;
    QStringList lines = QStringList::split("\n", gettextComment);
    for( QStringList::Iterator it = lines.begin() ; it!=lines.end() ; ++it)
    {
	QString curLine = (*it);
	if( curLine.startsWith("#:") ) curLine = curLine.mid(2);
	curLine = curLine.stripWhiteSpace();
	
	QStringList refs=QStringList::split(" ",curLine);
	
	for( QStringList::Iterator it=refs.begin(); it!=refs.end(); ++it)
	{
	     references.push_back( *it );
	}
    }
    
    QValueList<ContextInfo> results;
    QRegExp re(":\\d+");
    
    for( QStringList::Iterator it = references.begin() ; it!=references.end() ; ++it)
    {
	QString curRef = (*it);
	curRef.findRev(re);
	if( re.pos(0)+re.cap(0).length() == curRef.length() )
	{
	    QString lineNum = re.cap(0).mid(1);
	    QString fileName = curRef.mid( 0, curRef.length()-re.matchedLength() );
	    for( QStringList::Iterator it1 = prefixes.begin(); it1!=prefixes.end() ; ++it1 )
	    {
		QString path = (*it1);
		path.replace( "@COMMENTPATH@", fileName);
		
		QFileInfo url(path);
		if( url.exists())
		{
		    ContextInfo ref;
		    ref.path = url.absFilePath();
		    ref.line = lineNum.toInt();
		    results.append(ref);
		}
	    }
	}
    }
    
    return results;
}

bool SourceContext::loadPart()
{
    KTrader::OfferList offers = KTrader::self()->query( "KTextEditor/Document" );
    if( offers.count() < 1 )
    {
	KMessageBox::error(this,i18n("KBabel cannot start a text editor component.\n"
	"Please check your KDE installation."));
	_part=0;
	_view=0;
	return false;
    }
    KService::Ptr service = *offers.begin();
    KLibFactory *factory = KLibLoader::self()->factory( service->library().latin1() );
    if( !factory )
    {
	KMessageBox::error(this,i18n("KBabel cannot start a text editor component.\n"
	"Please check your KDE installation."));
	_part=0;
	_view=0;
	return false;
    }
    _part = static_cast<KTextEditor::Document *>( factory->create( this, 0, "KTextEditor::Document" ) );

    if( !_part )
    {
	KMessageBox::error(this,i18n("KBabel cannot start a text editor component.\n"
	"Please check your KDE installation."));
	_part=0;
	_view=0;
	return false;
    }
    _view = _part->createView( this, 0 );
    _layout->addWidget(static_cast<QWidget *>(_view), 1);
    static_cast<QWidget *>(_view)->show();

    return true;
}

void SourceContext::setProject( KBabel::Project::Ptr project )
{
    _project = project;
}

#include "context.moc"
