/****************************************************************************
**
** Copyright (C) 2003-2006 Frank Hemer <frank@hemer.org>,
**                         Tilo Riemer <riemer@crossvc.com>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** 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 "UpdateOtherRevisionDialogImpl.h"

#include <qradiobutton.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qdatetimeedit.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <qmessagebox.h>
#include <qtimer.h>
#include <qwhatsthis.h>

#include "globals.h"
#include "Validators.h"
#include "pixmapcache.h"

UpdateOtherRevisionDialogImpl::UpdateOtherRevisionDialogImpl(bool dirOnly, QStringList *tagList, 
							     QString moduleName, QString caption,
							     const QIconSet &whatsThisIconSet,
							     QWidget *parent, const char *name, bool modal, WFlags f)
//  : UpdateOtherRevisionDialog(LookAndFeel::g_b0AsParent ? 0 : parent, name, modal, f),
  : UpdateOtherRevisionDialog(modal ? parent : (LookAndFeel::g_b0AsParent ? 0 : parent),
			      name, modal, f),
    m_parent(parent), m_name(FetchButton->name()),
    m_pSelectedTagList(tagList), m_topModuleName(moduleName),
    m_dirOnly(dirOnly), m_fetchOverall(TRUE),
    m_listOnEdit(FALSE), m_pOldPixmap(NULL),
    m_lastLen(0), m_running(false)
{

  m_pWhatsThis->setIconSet(whatsThisIconSet);
#ifdef Q_WS_MAC
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height() * 2);
#else
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height());
#endif

  m_Revision->setValidator(new RevisionValidator(m_Revision));
  m_TagBox->setAutoCompletion(FALSE);
  m_TagBox->setValidator(new TagValidator(m_TagBox));
  connect( m_TagBox, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString &)));
  connect( m_TagBox, SIGNAL(activated(const QString &)), this, SLOT(activated(const QString &)));
  connect( m_TagBox->lineEdit(), SIGNAL(selectionChanged()), this, SLOT(setSelection()));

  if (m_dirOnly) {
    TagButton->setChecked(TRUE);
    RevisionButton->setChecked(FALSE);
    RevisionButton->setEnabled(FALSE);
    RevisionButton->hide();
    m_Revision->hide();
  }
  tagListUpdated();
  m_Date->dateEdit()->setOrder(LookAndFeel::g_dateTimeOrder);
  m_Date->setDateTime(QDateTime::currentDateTime());
  StickyTagCheckBox->setChecked(TRUE);
  setCaption(caption);
  QTimer::singleShot(0,this,SLOT(updateSize()));
}

QSize UpdateOtherRevisionDialogImpl::sizeHint () const {
  QSize s = UpdateOtherRevisionDialog::sizeHint();
  s.setWidth(UpdateOtherRevisionDialog::width());
  return s;
}

void UpdateOtherRevisionDialogImpl::updateSize() {
  adjustSize();
}

void UpdateOtherRevisionDialogImpl::readProjectNameList() {
  m_ProjectTagList.clear();
  projectSettings->get(m_topModuleName,PROJECTTAGLIST,m_ProjectTagList);
}

QString UpdateOtherRevisionDialogImpl::cvsParameter() {

   QString param = "";
   
   if ( useStickyTag() ) {
      if ( ResetStickyTagButton->isChecked() ) param = "-A";
      else {
         QString txt;
         if ( m_Revision->isEnabled() ) {
            txt = m_Revision->text().stripWhiteSpace();
            if ( !txt.isEmpty() ) param += "-r " + txt;
         } else {
            if (m_TagBox->isEnabled()) {
               txt = m_TagBox->currentText();
               txt = txt.mid(txt.findRev(" ")+1).stripWhiteSpace();
               if ( !txt.isEmpty() )  param += "-r " + txt;
            }
            if (m_Date->isEnabled()) {
               if (!param.isEmpty()) param += " ";
               param += "-D " + masqWs(m_Date->dateTime().toString("yyyy-MM-dd hh:mm:ss"));
            }
         }
      }
   } else {
      QString txt;
      if (m_Revision->isEnabled()) {
         txt = m_Revision->text().stripWhiteSpace();
         if (!txt.isEmpty()) {
            param += txt;
         }
      } else if (m_TagBox->isEnabled()) {
         txt = m_TagBox->currentText();
         txt = txt.mid(txt.findRev(" ")+1).stripWhiteSpace();
         if (!txt.isEmpty()) {
            param += txt;
         }
      }
      if (m_Date->isEnabled()) {
         txt = m_Date->dateTime().toString("yyyy-MM-dd hh:mm:ss");
         if (!txt.isEmpty()) {
            param += ":"+txt;
         }
      }
   }
   return param;
}

bool UpdateOtherRevisionDialogImpl::useStickyTag() {
  return (!StickyTagCheckBox->isEnabled() || StickyTagCheckBox->isChecked());
}

void UpdateOtherRevisionDialogImpl::resetStickyTagToggled(bool state) {
  if (!m_dirOnly) RevisionButton->setDisabled(state);
  TagButton->setDisabled(state);
  DateButton->setDisabled(state);
  SetStickyTagGroupBox->setDisabled(state);
  DetailFrame->setDisabled(state);
}

void UpdateOtherRevisionDialogImpl::revisionClicked(bool state) {
  if (!m_dirOnly && state) TagButton->setChecked(!state);
  if (!m_dirOnly && state) DateButton->setChecked(!state);
}

void UpdateOtherRevisionDialogImpl::tagClicked(bool state) {
  if (!m_dirOnly && state) RevisionButton->setChecked(!state);
}

void UpdateOtherRevisionDialogImpl::dateClicked(bool state) {
  if (!m_dirOnly && state) RevisionButton->setChecked(!state);
}

void UpdateOtherRevisionDialogImpl::setStickyTagClicked(bool state) {
  if (!state) {
    showWarning();
  }
}

void UpdateOtherRevisionDialogImpl::okClicked() {
  if (cvsParameter().isEmpty()) {
    QString txt = tr("You need to at least fill in one of:\n\n\t- revision\n\t- tag\n\t- date\n");
    QMessageBox::critical(this,tr("Error"),txt,QMessageBox::Ok,QMessageBox::NoButton);
  } else accept();
}

void UpdateOtherRevisionDialogImpl::showWarning() {
  QString txt = tr(
    "Updating without setting sticky tags is dangerous!<br>"
    "If no revision/tag is specified, the main trunk is assumed. "
    "To make sure all files are reverted to exactly what you want "
    "requires manually setting a regular tag and specifying this as "
    "the tag to update to.<br>"
    "Carefully watch the cvs output and make sure "
    "cvs really does what you want.");
  QMessageBox::information(this,tr("Warning"),txt,QMessageBox::Ok);
}

void UpdateOtherRevisionDialogImpl::fetchClicked() {

   if (m_running ^= true) {//not running
      FetchButton->setName("stop action");
      FetchButton->setText(tr("Stop"));
      if (m_fetchOverall ^= TRUE) {//overall mode
         emit getProjectTags();
      } else {
         emit getSelectedTags();
      }
   } else {
      QTimer::singleShot(0,m_parent,SLOT(stopCurAction()));
      FetchButton->setName(m_name);
      if (m_fetchOverall ^= TRUE) {//overall mode
         FetchButton->setText( tr("Fetch selected"));
      } else {
         FetchButton->setText( tr("Fetch all"));
      }
   }
}

void UpdateOtherRevisionDialogImpl::tagListUpdated() {

   m_running = false;
   if (!globalStopAction) {
      m_listOnUpdate = TRUE;
      m_listOnEdit = FALSE;
      m_TagBox->clear();
      FetchButton->setName(m_name);
      if (m_fetchOverall) {
         FetchButton->setText( tr("Fetch selected"));
         readProjectNameList();
         m_TagBox->insertStringList(m_ProjectTagList);
      } else {
         FetchButton->setText( tr("Fetch all"));
         m_TagBox->insertStringList(*m_pSelectedTagList);
      }
      setPixmaps();
      m_oldText = m_TagBox->currentText();
      m_listOnUpdate = FALSE;
  }
}

void UpdateOtherRevisionDialogImpl::setPixmaps() {
   int i;
   for (i = 0; i < m_TagBox->count(); ++i) {
      QString txt = m_TagBox->text(i);
      if (txt.startsWith("T: ")) m_TagBox->changeItem(findEmbeddedPixmap("TagTag30x16"),txt.mid(3),i);
      else if (txt.startsWith("B: ")) m_TagBox->changeItem(findEmbeddedPixmap("BranchTag30x16"),txt.mid(3),i);
   }
   m_oldTagIdx = 0;
   if (i == 0) {
      m_TagBox->insertItem(findEmbeddedPixmap("Tag30x16"),"",m_oldTagIdx);
   }
   m_TagBox->setCurrentItem(m_oldTagIdx);//removes T: or B: for the lineEdit
}

void UpdateOtherRevisionDialogImpl::setSelection() {

  if (m_listOnUpdate) return;

  int start;
  int end;
  if (m_TagBox->lineEdit()->getSelection(&start,&end)) {
    m_lastLen = start;
  }
}

void UpdateOtherRevisionDialogImpl::activated(const QString & s) {

  if (m_pOldPixmap) {
    m_TagBox->changeItem(*m_pOldPixmap,m_oldText,m_oldTagIdx);
    m_pOldPixmap = NULL;
  }
  m_oldText = s;
  m_oldTagIdx = m_TagBox->currentItem();
  m_listOnEdit = FALSE;
}

void UpdateOtherRevisionDialogImpl::textChanged(const QString &txt) {

  if (m_listOnUpdate) return;
  
  int idx = -1;
  for (int i = 0; i<m_TagBox->count(); ++i) {
     if (m_TagBox->text(i).startsWith(txt)) {
        idx = i;
        break;
     }
  }
  
  if (idx > -1 && (m_lastLen < (int)txt.length()) || (m_TagBox->text(idx).length() == txt.length()) ) {
     
     m_listOnUpdate = TRUE;
     int cursorPos = m_TagBox->lineEdit()->cursorPosition();
     m_TagBox->setCurrentItem(idx);
     QString current = m_TagBox->currentText();
     activated(current);
     if (current.length() != txt.length()) m_TagBox->lineEdit()->setSelection(txt.length(),current.length()-txt.length());
     else m_TagBox->lineEdit()->setCursorPosition(cursorPos);
     m_listOnUpdate = FALSE;
     
  } else if (m_oldTagIdx == m_TagBox->currentItem()) {
     
     if (!m_listOnEdit) {
        m_listOnEdit = TRUE;
        QPixmap const * p = m_TagBox->pixmap(m_oldTagIdx);
        if (p) {
           m_pOldPixmap = new QPixmap(*p);
        } else {
           m_pOldPixmap = NULL;
        }
        m_TagBox->changeItem(findEmbeddedPixmap("Tag30x16"),m_oldText,m_oldTagIdx);
     }
     
  }
  m_lastLen = txt.length();
}

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

