/****************************************************************************
**
** Copyright (C) 2001-2006 Frank Hemer <frank@hemer.org>,
**                         Tilo Riemer <riemer@crossvc.com>,
**                         Jose Hernandez <joseh@tesco.net>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** CrossVC is available under two different licenses:
**
** If CrossVC is linked against the GPLed version of Qt 
** CrossVC is released under the terms of GPL also.
**
** If CrossVC is linked against a nonGPLed version of Qt 
** CrossVC is released under the terms of the 
** CrossVC License for non-Unix platforms (CLNU)
**
**
** CrossVC License for non-Unix platforms (CLNU):
**
** Redistribution and use in binary form, without modification, 
** are permitted provided that the following conditions are met:
**
** 1. Redistributions in binary form must reproduce the above copyright
**    notice, this list of conditions and the following disclaimer in the
**    documentation and/or other materials provided with the distribution.
** 2. It is not permitted to distribute the binary package under a name
**    different than CrossVC.
** 3. The name of the authors may not be used to endorse or promote
**    products derived from this software without specific prior written
**    permission.
** 4. The source code is the creative property of the authors.
**    Extensions and development under the terms of the Gnu Public License
**    are limited to the Unix platform. Any distribution or compilation of 
**    the source code against libraries licensed other than gpl requires 
**    the written permission of the authors.
**
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR 
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**
**
** CrossVC License for Unix platforms:
**
** 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, version 2 of the License.
** 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 version 2 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
*****************************************************************************/

#include "config.h"

#include <qlistview.h>
#include <qstringlist.h>
#include <qapplication.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qwhatsthis.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qsizegrip.h>

#ifndef Q_WS_WIN
#include <unistd.h>
#else
#include <io.h>
#endif

#include "globals.h"
#include "tzconvert.h"
#include "HistoryDialogImpl.h"
#include "DirBase.h"

/* 
 *  Constructs a HistoryDialogImpl which is a child of 'parent', with the 
 *  name 'name' and widget flags set to 'f' 
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
HistoryDialogImpl::HistoryDialogImpl(const QIconSet &whatsThisIconSet, 
      QWidget * parent, WFlags fl )
   : HistoryDialog( LookAndFeel::g_b0AsParent ? 0 : parent, "HistoryDlg", fl )
{
   m_pWhatsThis->setIconSet(whatsThisIconSet);
#ifdef Q_WS_MAC
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height() * 2);
#else
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height());
#endif
   ButtonLayout->addWidget(new QSizeGrip(this),0,Qt::AlignRight|Qt::AlignBottom);

   HistoryList->setSorting(1);
   connect(HistoryList, SIGNAL(doubleClicked(QListViewItem *)), this, SLOT(viewFile(QListViewItem *)) );
}

/*  
 *  Destroys the object and frees any allocated resources
 */
HistoryDialogImpl::~HistoryDialogImpl()
{
   // no need to delete child widgets, Qt does it all for us
}

void HistoryDialogImpl::parseHistory ( CvsBuffer *output, QString dir, QDir* topDir, QString name, QString revision) {

   setCaption ("CVS History - " + name + " " + revision);

   m_basedir = ((DirBase*)topDir)->fullName();
   m_topModule = ((DirBase*)topDir)->relativeName();
   unsigned int len = (*output).numLines();
   unsigned int index = 0;
   QString line;
   for (unsigned int i = outputLineOffset; i<len;i++) {
      line = (*output).textLine(i);
      if (line.isEmpty()) continue;
      
      QStringList list = QStringList::split (' ', line);
      QString cmd = list[0];
      if (cmd.length() != 1)
         continue;
      
      int ncol = (int)list.count();
      
      QChar cmd_code = cmd[0];
      switch (cmd_code) {
         case 'F': {
            if (ncol == 7) {//history only lists the workdir name, so we can't compare
               if (list[5].find(dir.left(3)) > -1) {//instead compare first 3 chars
                  break;
               }
               continue;
            }
         }
         case 'O':
         case 'W':
         case 'E': {
            if (ncol == 8) {
               if ( list[5].startsWith( dir)) {
                  break;
               }
            } else if (ncol == 9) {
               if ( list[6].startsWith( dir)) {
                  break;
               }
            }
            continue; // only show history of current dir
         }
         default: {
            if (!list[7].startsWith( dir)) continue; // only show history of current dir
            break;
         }
      }
      
      FileListViewItem * item = NULL;
      QDateTime dateTime = QDateTime::fromString(list[1]+"T"+list[2],Qt::ISODate);
      dateTime = getAsLocal(dateTime,FALSE);
      QString dateTxt = dateTime.toString(LookAndFeel::g_dateTimeFormat) + " " + list[3];

      QString event;
      switch (cmd_code) {
	 case 'O': event = tr("Checkout ");         break;
	 case 'C': event = tr("Update, Conflict "); break;
	 case 'G': event = tr("Update, Merged ");   break;
	 case 'U': event = tr("Update, Copied ");   break;
	 case 'P': event = tr("Update, Patched ");  break;
	 case 'W': {
	    event = tr("Update, Deleted ");
	    if (ncol == 9) {
	       item = new FileListViewItem (HistoryList,
		     QString().sprintf(" %05d ", index),FileListViewItem::Num,
		     "",FileListViewItem::Date,
		     event,FileListViewItem::Text,
		     list[4],FileListViewItem::TextNoCase,
		     "",FileListViewItem::Rev,
		     list[5],FileListViewItem::TextNoCase,
		     list[6],FileListViewItem::Text);
	       item->setDate(1,&dateTime,dateTxt);
	       index++;
	       continue;
	    }
	    break;
	 }
	 case 'A': event = tr("Commit, Added ");    break;
	 case 'M': event = tr("Commit, Modified "); break;
	 case 'R': event = tr("Commit, Removed ");  break;
	 case 'T': event = tr("Tag ");              break;
	 case 'F': event = tr("Release ");          break;
	 case 'E': event = tr("Export ");           break;
	 default:  event = tr("Unknown ");          continue;
      }
    
      switch (ncol) {
	 case 10: {
	    item = new FileListViewItem (HistoryList,
		  QString().sprintf(" %05d ", index),FileListViewItem::Num,
		  "",FileListViewItem::Date,
		  event,FileListViewItem::Text,
		  list[4],FileListViewItem::TextNoCase,
		  list[5],FileListViewItem::Rev,
		  list[6],FileListViewItem::TextNoCase,
		  list[7],FileListViewItem::Text);
	    break;
	 }
	 case 9: {
	    item = new FileListViewItem (HistoryList,
		  QString().sprintf(" %05d ", index),FileListViewItem::Num,
		  "",FileListViewItem::Date,
		  event,FileListViewItem::Text,
		  list[4],FileListViewItem::TextNoCase,
		  list[5],FileListViewItem::Rev,
		  "",FileListViewItem::None,
		  list[6],FileListViewItem::Text);
	    break;
	 }
	 case 8:	{
	    item = new FileListViewItem (HistoryList,
		  QString().sprintf(" %05d ", index),FileListViewItem::Num,
		  "",FileListViewItem::Date,
		  event,FileListViewItem::Text,
		  list[4],FileListViewItem::TextNoCase,
		  "",FileListViewItem::Rev,
		  "",FileListViewItem::None,
		  list[5],FileListViewItem::Text);
	    break;
	 }
	 case 7: {
	    item = new FileListViewItem (HistoryList,
		  QString().sprintf(" %05d ", index),FileListViewItem::Num,
		  "",FileListViewItem::Date,
		  event,FileListViewItem::Text,
		  list[4],FileListViewItem::TextNoCase,
		  "",FileListViewItem::Rev,
		  "",FileListViewItem::None,
		  list[5].mid(1,list[5].length()-2),FileListViewItem::Text);
	    break;
	 }
      }
      if (item) item->setDate(1, &dateTime, dateTxt);

      index++;
   }
}

void HistoryDialogImpl::viewFile(QListViewItem *item) {

   if (item) {
      QString dir = item->text(6);
      displayFileRevision( item->text(4), item->text(6), item->text(5));
   }
}

void HistoryDialogImpl::displayFileRevision(QString rev, QString module,
      QString fname)
{
   QString tmpName = fname;
   tmpViewFileName = createTempFile() + "-" + rev + "-" + tmpName.replace("\"", "_");
   QString cvsRoot = "-Q checkout -p -n -r " + rev + " " +
      masqWs(module + "/" + fname.replace("\"", PLACEHOLDER_FOR_QUOTATION_MARKS)) + " > " + tmpViewFileName;
   QString file = "";
   callInteractive( m_topModule, m_basedir, cvsRoot,
	 file, CVS_EDIT_REVISION_CMD,
	 ExtApps::g_cvsRsh.path,  //additional options of cvsRsh not supported yet
	 true);
}

void HistoryDialogImpl::setEnabled(bool state) {
   HistoryList->setEnabled(state);
   buttonOk->setEnabled(state);
}

void HistoryDialogImpl::cvsCallStarted() {
   setEnabled(FALSE);
   QApplication::setOverrideCursor(Qt::waitCursor);
}

void HistoryDialogImpl::cvsCallFinished() {
   QApplication::restoreOverrideCursor();
   setEnabled(TRUE);
}

void HistoryDialogImpl::afterCall( int cmd, CvsBuffer*, bool failed) {
   cvsCallFinished();
   if (failed) return;
   switch( cmd) {
      case CVS_EDIT_REVISION_CMD: {
	 QFile tmpFile(tmpViewFileName);
	 setPermission(tmpFile, READABLE);//don't think you could change the file
	 emit editFile(tmpViewFileName);
	 break;
      }
   }
}

void HistoryDialogImpl::enterWhatsThisMode()
{
   QWhatsThis::enterWhatsThisMode();
}



syntax highlighted by Code2HTML, v. 0.9.1