/****************************************************************************
**
** 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 "RevisionWidgetImpl.h"

#include <qframe.h>
#include <qradiobutton.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qbuttongroup.h>
#include <qdatetimeedit.h>
#include <qstringlist.h>
#include <qtimer.h>

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

RevisionWidgetImpl::RevisionWidgetImpl ( QWidget * parent,
					 const char * name,
					 WFlags f )
  : RevisionWidget(parent,name,f),
    m_connectionSrc(NULL),
    m_name(FetchButton->name()),
    m_topModuleName(QString::null),
    m_fetchOverall(TRUE),
    m_listOnEdit(FALSE),
    m_pOldPixmap(NULL),
    m_lastLen(0),
    m_running(false)
{
  
  m_Revision->setValidator(new RevisionValidator(m_Revision));
  m_TagBox->setValidator(new TagValidator(m_TagBox));

}

RevisionWidgetImpl::~RevisionWidgetImpl () {

}
/* Initializes the widget
 * if connectionSrc is NULL, fetching will be disabled and tagList will be used to fill the list (if not NULL)
 * else:
 * if tagList is not NULL, click on 'Fetch' will emit connectionSrc->SLOT(readCurrentTagList())
 * if moduleName is not QString::null, click on 'Fetch' will emit connectionSrc->SLOT(updateProjectTagList())
 */
void RevisionWidgetImpl::init( QObject * connectionSrc,
			       QStringList * tagList,
			       QString moduleName ) {

  m_pSelectedTagList = tagList;
  m_topModuleName = moduleName;
  m_connectionSrc = connectionSrc;

  m_TagBox->setAutoCompletion(FALSE);
  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 (connectionSrc != NULL) {

    connect( connectionSrc, SIGNAL(tagListFetched()), this, SLOT(tagListUpdated()));

    if (m_topModuleName != QString::null) {
      connect( this, SIGNAL(getProjectTags()), connectionSrc, SLOT(updateProjectTagList()) );
    } else {
      m_fetchOverall = FALSE;
    }
    if (tagList != NULL) {
      connect( this, SIGNAL(getSelectedTags()), connectionSrc, SLOT(readCurrentTagList()));
    }

  } else {

    disableTagFetch();
    activateHead();
    m_fetchOverall = FALSE;

  }

  tagListUpdated();
  m_DateTime->dateEdit()->setOrder(LookAndFeel::g_dateTimeOrder);
  m_DateTime->setDateTime(QDateTime::currentDateTime());
}

void RevisionWidgetImpl::setEnabled(bool state) {
   HeadButton->setEnabled(state);
   OtherButton->setEnabled(state);
   SetStickyTagButton->setEnabled(state);
   TagDateButton->setEnabled(state);
   RevisionButton->setEnabled(state);
   m_TagBox->setEnabled(state);
   TagButton->setEnabled(state);
   DateButton->setEnabled(state);
   m_DateTime->setEnabled(state && DateButton->isChecked());
}

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

void RevisionWidgetImpl::hideStickyTagFrame() {
  StickyTagFrame->hide();
}

void RevisionWidgetImpl::hideRevisionFrame() {
  RevisionButton->hide();
  m_Revision->hide();
  TagDateButton->setChecked(TRUE);
}

void RevisionWidgetImpl::disableTagFetch() {
  FetchButton->hide();
}

void RevisionWidgetImpl::activateHead() {
  HeadButton->setChecked(TRUE);
}

bool RevisionWidgetImpl::isStickySet() {
  return (StickyTagFrame->isEnabled() && SetStickyTagButton->isChecked());
}

bool RevisionWidgetImpl::isHeadSet() {
  return HeadButton->isChecked();
}

QString RevisionWidgetImpl::getRevision() {
  if (m_Revision->isEnabled()) return m_Revision->text().stripWhiteSpace();
  else return QString::null;
}

QString RevisionWidgetImpl::getTag() {
  if (m_TagBox->isEnabled()) return m_TagBox->currentText().stripWhiteSpace();
  else return QString::null;
}

QString RevisionWidgetImpl::getDateTime() {
  if (m_DateTime->isEnabled()) return m_DateTime->dateTime().toString("yyyy-MM-dd hh:mm:ss");
  else return QString::null;
}

void RevisionWidgetImpl::fetchClicked() {

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


}

void RevisionWidgetImpl::setStickyTagToggled(bool state) {
  emit stickyTagToggled(state);
}

void RevisionWidgetImpl::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"));
      if (m_pSelectedTagList) m_TagBox->insertStringList(*m_pSelectedTagList);
    }
    setPixmaps();
    m_oldText = m_TagBox->currentText();
    m_listOnUpdate = FALSE;
  }
}

void RevisionWidgetImpl::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 RevisionWidgetImpl::setSelection() {

  if (m_listOnUpdate) return;

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

void RevisionWidgetImpl::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 RevisionWidgetImpl::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();
}



syntax highlighted by Code2HTML, v. 0.9.1