/*
   Copyright (C) 2002 by Roberto Raggi <roberto@kdevelop.org>
   Copyright (C) 2005 by Nicolas Escuder <n.escuder@intra-links.com>

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

   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 Steet, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "phperrorview.h"
#include "phpsupportpart.h"

#include <kdevpartcontroller.h>
#include <kdevmainwindow.h>
#include <kdevproject.h>

#include <tdeversion.h>
#include <tdeparts/part.h>
#include <tdetexteditor/editinterface.h>
#include <tdetexteditor/document.h>
#include <tdetexteditor/markinterface.h>

#include <tdetexteditor/markinterfaceextension.h>
#include <tdetexteditor/view.h>

#include <kdebug.h>
#include <tdelocale.h>
#include <kstatusbar.h>
#include <kurl.h>
#include <tdeapplication.h>
#include <kiconloader.h>
#include <kdialogbase.h>

#include <tdeconfig.h>

#include <tqtimer.h>
#include <tqregexp.h>
#include <tqvbox.h>
#include <tqfileinfo.h>
#include <tqwhatsthis.h>
#include <tqtabbar.h>
#include <tqwidgetstack.h>
#include <tqlayout.h>
#include <tqlineedit.h>

class ProblemItem: public TDEListViewItem
{
public:
    ProblemItem( TQListView* parent, const TQString& problem,
       const TQString& file, const TQString& line, const TQString& column  )
   : TDEListViewItem( parent, problem, file, line, column ) {}

    ProblemItem( TQListViewItem* parent, const TQString& problem,
       const TQString& file, const TQString& line, const TQString& column  )
   : TDEListViewItem( parent,  problem, file, line, column ) {}

    int compare( TQListViewItem* item, int column, bool ascending ) const {
   if( column == 2 || column == 3 ){
       int a = text( column ).toInt();
       int b = item->text( column ).toInt();
       if( a == b )
      return 0;
       return( a > b ? 1 : -1 );
   }
   return TDEListViewItem::compare( item, column, ascending );
    }

};

PHPErrorView::PHPErrorView( PHPSupportPart* part, TQWidget* parent, const char* name )
    : TQWidget( parent, name ? name : "problemreporter" ),
      m_phpSupport( part ),
      m_document( 0 ),
      m_markIface( 0 )
{
    TQWhatsThis::add(this, i18n("<b>Problem reporter</b><p>This window shows various \"problems\" in your project. "
        "It displays TODO entries, FIXME's and errors reported by a language parser. "
        "To add a TODO or FIXME entry, just type<br>"
        "<tt>//@todo my todo</tt><br>"
        "<tt>//TODO: my todo</tt><br>"
        "<tt>//FIXME fix this</tt>"));

    m_gridLayout = new TQGridLayout(this,2,3);

    m_errorList = new TDEListView(this);
    m_fixmeList = new TDEListView(this);
    m_todoList = new TDEListView(this);
    m_filteredList = new TDEListView(this);
    m_currentList = new TDEListView(this);

    m_filteredList->addColumn( i18n("Level") );
    m_currentList->addColumn( i18n("Level") );

    //addColumn( i18n("Level") );
    InitListView(m_errorList);
    InitListView(m_fixmeList);
    InitListView(m_todoList);
    InitListView(m_filteredList);
    InitListView(m_currentList);
    m_currentList->removeColumn(1);

    m_widgetStack = new TQWidgetStack(this);
    m_widgetStack->addWidget(m_currentList,0);
    m_widgetStack->addWidget(m_errorList,1);
    m_widgetStack->addWidget(m_fixmeList,2);
    m_widgetStack->addWidget(m_todoList,3);
    m_widgetStack->addWidget(m_filteredList,4);

    m_tabBar = new TQTabBar(this);
    m_tabBar->insertTab(new TQTab(i18n("Current")),0);
    m_tabBar->insertTab(new TQTab(i18n("Errors")),1);
    m_tabBar->insertTab(new TQTab(i18n("Fixme")),2);
    m_tabBar->insertTab(new TQTab(i18n("Todo")),3);
    m_tabBar->insertTab(new TQTab(i18n("Filtered")),4);
    m_tabBar->setTabEnabled(0,false);
    m_tabBar->setTabEnabled(4,false);

    m_tabBar->setCurrentTab(0);

    m_filterEdit = new KLineEdit(this);

    TQLabel* m_filterLabel = new TQLabel(i18n("Lookup:"),this);

    m_gridLayout->addWidget(m_tabBar,0,0);
    m_gridLayout->addMultiCellWidget(m_widgetStack,1,1,0,2);
    m_gridLayout->addWidget(m_filterLabel,0,1,TQt::AlignRight);
    m_gridLayout->addWidget(m_filterEdit,0,2,TQt::AlignLeft);

    connect( m_filterEdit, TQT_SIGNAL(returnPressed()), this, TQT_SLOT(slotFilter()) );
    connect( m_filterEdit, TQT_SIGNAL(textChanged( const TQString & )), this, TQT_SLOT(slotFilter()) );
    connect( m_tabBar, TQT_SIGNAL(selected(int)), this, TQT_SLOT(slotTabSelected(int)) );
    connect( part->partController(), TQT_SIGNAL(activePartChanged(KParts::Part*)), this, TQT_SLOT(slotActivePartChanged(KParts::Part*)) );
    connect( part->partController(), TQT_SIGNAL(partAdded(KParts::Part*)), this, TQT_SLOT(slotPartAdded(KParts::Part*)) );
    connect( part->partController(), TQT_SIGNAL(partRemoved(KParts::Part*)), this, TQT_SLOT(slotPartRemoved(KParts::Part*)) );

    slotActivePartChanged( part->partController()->activePart() );
}

void PHPErrorView::slotFilter()
{
    if(!m_tabBar->isTabEnabled(4))
      m_tabBar->setTabEnabled(4,true);

    m_tabBar->tab(4)->setText(i18n("Filtered: %1").arg( m_filterEdit->text() ));
    m_tabBar->setCurrentTab(4);

    m_filteredList->clear();

    filterList(m_errorList,i18n("Error"));
    filterList(m_fixmeList,i18n("Fixme"));
    filterList(m_todoList,i18n("Todo"));

}

void PHPErrorView::filterList(TDEListView* listview, const TQString& level)
{
    TQListViewItemIterator it( listview );
    while ( it.current() ) {
        if ( it.current()->text(3).contains(m_filterEdit->text(),false))
       new TDEListViewItem(m_filteredList,level,
       it.current()->text(0),it.current()->text(1),it.current()->text(2),it.current()->text(3));
        ++it;
    }
}

void PHPErrorView::slotTabSelected( int tabindex )
{
    m_widgetStack->raiseWidget(tabindex);
}

void PHPErrorView::InitListView(TDEListView* listview)
{
    listview->addColumn( i18n("File") );
    listview->addColumn( i18n("Line") );
    listview->addColumn( i18n("Column") );
    listview->addColumn( i18n("Problem") );
    listview->setAllColumnsShowFocus( TRUE );

    connect( listview, TQT_SIGNAL(executed(TQListViewItem*)),
             this, TQT_SLOT(slotSelected(TQListViewItem*)) );

    connect( listview, TQT_SIGNAL(returnPressed(TQListViewItem*)),
             this, TQT_SLOT(slotSelected(TQListViewItem* )) );

}

PHPErrorView::~PHPErrorView()
{
}

void PHPErrorView::slotActivePartChanged( KParts::Part* part )
{
   if ( !part ) {
      m_tabBar->setTabEnabled(0,false);
      return;
   }

   if ( m_document )
      disconnect( m_document, 0, this, 0 );

   m_document = dynamic_cast<KTextEditor::Document*>( part );
   m_markIface = 0;

   if ( !m_document ) {
      m_tabBar->setTabEnabled(0,false);
      return;
   }

   m_fileName = m_document->url().path();

   initCurrentList();

   m_markIface = dynamic_cast<KTextEditor::MarkInterface*>( part );
}

void PHPErrorView::removeAllItems( TQListView* listview, const TQString& filename )
{
   TQListViewItem* current = listview->firstChild();
   while( current ){
      TQListViewItem* i = current;
      current = current->nextSibling();

      if( i->text(0) == filename )
         delete( i );
   }
}

void PHPErrorView::removeAllProblems( const TQString& filename )
{
   TQString relFileName = filename;
   relFileName.remove(m_phpSupport->project()->projectDirectory());

   kdDebug(9008) << "PHPErrorView::removeAllProblems()" << relFileName << endl;

   if (filename == m_fileName)
      m_currentList->clear();

   removeAllItems(m_errorList,relFileName);
   removeAllItems(m_fixmeList,relFileName);
   removeAllItems(m_todoList,relFileName);

   if ( m_document && m_markIface ) {
      TQPtrList<KTextEditor::Mark> marks = m_markIface->marks();
      TQPtrListIterator<KTextEditor::Mark> it( marks );
      while( it.current() ) {
         m_markIface->removeMark( it.current()->line, KTextEditor::MarkInterface::markType07 );
         ++it;
      }
   }
}

void PHPErrorView::initCurrentList()
{
   m_tabBar->setTabEnabled(0,true);

   TQString relFileName = m_fileName;

   if (m_phpSupport->project())
      relFileName.remove(m_phpSupport->project()->projectDirectory());

   m_currentList->clear();

   updateCurrentWith(m_errorList, i18n("Error"),relFileName);
   updateCurrentWith(m_fixmeList,i18n("Fixme"),relFileName);
   updateCurrentWith(m_todoList,i18n("Todo"),relFileName);
}

void PHPErrorView::updateCurrentWith(TQListView* listview, const TQString& level, const TQString& filename)
{
   TQListViewItemIterator it(listview);
   while ( it.current() ) {
      if ( it.current()->text(0) == filename)
         new TQListViewItem(m_currentList,level,it.current()->text(1),it.current()->text(2),it.current()->text(3));
      ++it;
   }
}

void PHPErrorView::slotSelected( TQListViewItem* item )
{
   bool is_filtered = false;
   bool is_current = false;

   if (item->listView() == m_filteredList)
      is_filtered = true;
   else if(item->listView() == m_currentList)
      is_current = true;

   KURL url( is_current ? m_fileName : item->text(0 + is_filtered) );
   int line = item->text( 1 + is_filtered).toInt();
   m_phpSupport->partController()->editDocument( url, line-1 );
}

void PHPErrorView::reportProblem( int level, const TQString& fileName, int line, const TQString& text)
{
   int markType = levelToMarkType( level );
   if ( markType != -1 && m_document && m_markIface && m_fileName == fileName ) {
      m_markIface->addMark( line, markType );
   }

   TQString msg = text;
   msg = msg.replace( TQRegExp("\n"), "" );

   TQString relFileName = fileName;
   relFileName.remove(m_phpSupport->project()->projectDirectory());

   TDEListView* list;
   switch( level )
   {
      case Error:
      case ErrorNoSuchFunction:
      case ErrorParse:
      list = m_errorList;
      m_tabBar->setCurrentTab(m_tabBar->tab(1));
      break;

      case Warning:
      list = m_errorList;
      break;

      case Todo:
      list = m_todoList;
      break;

      case Fixme:
      list = m_fixmeList;
      break;

      default:
      list = NULL;
      break;
   }

   if (list) {
      kdDebug(9018) << "PB " << msg << endl;
      new ProblemItem( list, relFileName, TQString::number( line + 1 ), 0, msg );
   }

   if (fileName == m_fileName)
      new TQListViewItem(m_currentList, levelToString( level ), TQString::number( line + 1 ), 0, msg);
}

void PHPErrorView::slotPartAdded( KParts::Part* part )
{
   KTextEditor::MarkInterfaceExtension* iface = dynamic_cast<KTextEditor::MarkInterfaceExtension*>( part );

   if ( !iface )
      return;

   iface->setPixmap( KTextEditor::MarkInterface::markType07, SmallIcon("process-stop") );
}

void PHPErrorView::slotPartRemoved( KParts::Part* part )
{
   kdDebug(9007) << "PHPErrorView::slotPartRemoved()" << endl;
   if ( part == m_document ){
      m_document = 0;
   }
}

TQString PHPErrorView::levelToString( int level ) const
{
   switch( level )
   {
      case ErrorNoSuchFunction:
      return TQString( i18n("Undefined function") );

      case ErrorParse:
      return TQString( i18n("Parse Error") );

      case Error:
      return TQString( i18n("Error") );

      case Warning:
      return TQString( i18n("Warning") );

      case Todo:
      return TQString( i18n("Todo") );

      case Fixme:
      return TQString( i18n("Fixme") );

      default:
      return TQString();
    }

}

int PHPErrorView::levelToMarkType( int level ) const
{
   switch( level )
   {
      case ErrorNoSuchFunction:
      case ErrorParse:
      case Error:
      return KTextEditor::MarkInterface::markType07;

      case Warning:
      return -1;

      case Todo:
      return -1;

      case Fixme:
      return -1;

      default:
      return -1;
    }

}

#include "phperrorview.moc"
