/****************************************************************************
**
** Copyright (C) 2001-2006 Frank Hemer <frank@hemer.org>,
**                         Tilo Riemer <riemer@crossvc.com>
**                         Jose Hernandez <joseh@tesco.net>,
**                         Tom Mishima <tmishima@mail.at-m.or.jp>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** 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 <iostream>

#include <qdir.h>
#include <qfile.h>
#include <qcombobox.h>
#include <qlistbox.h>
#include <qtextstream.h>
#include <qmultilineedit.h>
#include <qregexp.h>
#include <qwhatsthis.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qtextcodec.h>
#include <qlayout.h>
#include <qsizegrip.h>

#include "CommitDialogImpl.h"
#include "globals.h"
#include "Validators.h"
#include "TextDecoder.h"
#include "TextEncoder.h"

QString CommitDialogImpl::s_comment = "";

CommitDialogImpl::CommitDialogImpl(const QIconSet &whatsThisIconSet,
      QWidget* parent,  
      const char* name, WFlags fl )
   : CommitDialog( LookAndFeel::g_b0AsParent ? 0 : parent, name, 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);

   templateField = 0;
    
   m_pRevision->setValidator( new RevisionValidator(m_pRevision));

   if (!s_comment.isEmpty()) {
      m_pComment->setText(s_comment);
   }

   connect( m_pTemplate, SIGNAL( activated( int ) ),
	 this, SLOT( selected( int ) ) );
   //   connect( m_pTemplate, SIGNAL( highlighted(const QString &) ),
   // 	   this, SLOT( lookupTip(const QString &) ) );
}

CommitDialogImpl::~CommitDialogImpl()
{
   // no need to delete child widgets, Qt does it all for us
}

void CommitDialogImpl::closeEvent(QCloseEvent *) {
   cancel();
}

void CommitDialogImpl::accept() {
   s_comment = m_pComment->text();
   store();
   emit acceptCvs();
}

void CommitDialogImpl::cancel() {
   s_comment = m_pComment->text();
   emit reject();
}

QString CommitDialogImpl::getRev() {
   if (m_pRevisionCheckBox->isChecked()) {
      return m_pRevision->text();
   } else {
      return "";
   }
}

QString CommitDialogImpl::getComment() {
   return m_pComment->text();
}

void CommitDialogImpl::reset() {
   m_pRevision->setText("");
   m_pRevisionCheckBox->setChecked(FALSE);
}

void CommitDialogImpl::updateTemplate()
{
   int i;
   for (i = m_pTemplate->count(); i>0; --i)
      m_pTemplate->removeItem(i-1);

   delete [] templateField;
   templateField = 0;    //needed if count <= 0...

   QString hstDir = tmpDir + "/Template";
   QDir d(hstDir);

   const QStringList list = d.entryList(QDir::Files | QDir::NoSymLinks, QDir::Time);
   QString str;
   int curItem = -1;
   int curPos = 0;
   int count = (int)list.count();
   if (count>0) {
      templateField = new QString[count];
   }

   for (i = 0; i < count; i++) {
      QFile tmpFile(hstDir + "/" + list[i]);
      if (tmpFile.open(IO_ReadOnly)) {
         QTextStream hstFile(&tmpFile); 
         hstFile.setCodec(I18n::g_pTextEncoder->pTextCodecPool()->pCodecForName(I18n::g_nameOfEncoder));
         str = hstFile.read();
         templateField[curPos] = str;
         tmpFile.close();
         
         str = str.replace( QRegExp("\\n")," ").simplifyWhiteSpace();
         QString abbrev = str.replace( QRegExp("[\\a\\f\\r\\t\\v]"),"");
         
         if (list[i] == "rcsinfo" && curItem == -1) {
            if (!str.isEmpty()) {
               m_pComment->setText(templateField[curPos]);
               curItem = curPos;
            }
         }
         
         if (!abbrev.isEmpty()) {
            m_pTemplate->insertItem(abbrev);
            if (m_pComment->text() == templateField[curPos]) curItem = curPos;
            curPos++;
         }
      }
      
      //remove all obsolete history files (i >= historySize)
      if ( (i >= HistorySize::g_commitinfo-1) && (list[i] != "rcsinfo") ) tmpFile.remove();
   }
   
   if (curItem > -1) m_pTemplate->setCurrentItem(curItem);
   if (m_pComment->text().isEmpty()) {
      m_pTemplate->setCurrentItem(0);
      if (count>0) {
         m_pComment->setText(templateField[0]);
      }
   }
}

void CommitDialogImpl::store()
{
   if (!m_pComment->text().isEmpty()) {
      QString newTxt = m_pComment->text().simplifyWhiteSpace();
      QString hstDir = tmpDir + "/Template";
      QDir d(hstDir);
      const QStringList list = d.entryList(QDir::Files | QDir::NoSymLinks, QDir::Time);
      for ( QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) {
	 if (*it == "rcsinfo") continue;
	 QFile tmpFile(hstDir + "/" + *it);
	 if (tmpFile.open(IO_ReadOnly)) {
	    QTextStream hstFile(&tmpFile); 
	    hstFile.setCodec(I18n::g_pTextEncoder->pTextCodecPool()->pCodecForName(I18n::g_nameOfEncoder));
	    QString txt = hstFile.read().simplifyWhiteSpace();
	    tmpFile.close();
	    if (txt == newTxt) {//file exists with older date => remove it
	       tmpFile.remove();
	       break;
	    }
	 }
      }
      writeUserHstFile(m_pComment->text());
   }
}

void CommitDialogImpl::clear()
{
   m_pComment->setFocus();
   m_pComment->clear();
}

void CommitDialogImpl::selected(int item)
{
   m_pComment->setText(templateField[item]);
}

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

void CommitDialogImpl::lookupTip (const QString & s) {
   int vwidth = m_pTemplate->listBox()->visibleWidth();
   QFontMetrics * m = new QFontMetrics(font());
   int swidth = m->width(s);
   if (swidth >= vwidth) {
      qDebug("tooltip: "+s);
   }
}



syntax highlighted by Code2HTML, v. 0.9.1