/*
**************************************************************************
                                 description
                             --------------------
    copyright            : (C) 2002 by Andreas Zehender
    email                : zehender@kde.org
**************************************************************************

**************************************************************************
*                                                                        *
*  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; either version 2 of the License, or     *
*  (at your option) any later version.                                   *
*                                                                        *
**************************************************************************/


#include "pmlatheedit.h"
#include "pmlathe.h"
#include "pmvectoredit.h"

#include <kdebug.h>
#include "pmglobals.h"

#include <qlayout.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <klocale.h>
#include <kdialog.h>
#include <kiconloader.h>
#include <kmessagebox.h>

PMLatheEdit::PMLatheEdit( QWidget* parent, const char* name )
      : Base( parent, name )
{
   m_pDisplayedObject = 0;
}

void PMLatheEdit::createTopWidgets( )
{
   Base::createTopWidgets( );

   QHBoxLayout* hl = new QHBoxLayout( topLayout( ) );
   hl->addWidget( new QLabel( i18n( "Spline type:" ), this ) );
   m_pSplineType = new QComboBox( false, this );
   m_pSplineType->insertItem( i18n( "Linear Spline" ) );
   m_pSplineType->insertItem( i18n( "Quadratic Spline" ) );
   m_pSplineType->insertItem( i18n( "Cubic Spline" ) );
   m_pSplineType->insertItem( i18n( "Bezier Spline" ) );
   hl->addWidget( m_pSplineType );
   hl->addStretch( 1 );

   connect( m_pSplineType, SIGNAL( activated( int ) ),
            SLOT( slotTypeChanged( int ) ) );
}

void PMLatheEdit::createBottomWidgets( )
{
   topLayout( )->addWidget( new QLabel( i18n( "Spline points:" ), this ) );
   m_pEditWidget = new QWidget( this );
   topLayout( )->addWidget( m_pEditWidget );
   m_pSturm = new QCheckBox( i18n( "Sturm" ), this );
   topLayout( )->addWidget( m_pSturm );
   connect( m_pSturm, SIGNAL( clicked( ) ), SIGNAL( dataChanged( ) ) );

   Base::createBottomWidgets( );
}

void PMLatheEdit::displayObject( PMObject* o )
{
   if( o->isA( PMTLathe ) )
   {
      bool readOnly = o->isReadOnly( );
      m_pDisplayedObject = ( PMLathe* ) o;

      switch( m_pDisplayedObject->splineType( ) )
      {
         case PMLathe::LinearSpline:
            m_pSplineType->setCurrentItem( 0 );
            break;
         case PMLathe::QuadraticSpline:
            m_pSplineType->setCurrentItem( 1 );
            break;
         case PMLathe::CubicSpline:
            m_pSplineType->setCurrentItem( 2 );
            break;
         case PMLathe::BezierSpline:
            m_pSplineType->setCurrentItem( 3 );
            break;
      }
      m_pSplineType->setEnabled( !readOnly );
      m_pSturm->setChecked( m_pDisplayedObject->sturm( ) );
      m_pSturm->setEnabled( !readOnly );
      displayPoints( m_pDisplayedObject->points( ) );

      Base::displayObject( o );
   }
   else
      kdError( PMArea ) << "PMLatheEdit: Can't display object\n";
}

void PMLatheEdit::displayPoints( const QValueList<PMVector>& sp )
{
   bool readOnly = m_pDisplayedObject->isReadOnly( );

   int np = ( int ) sp.count( );
   int ne = ( int ) m_edits.count( );

   if( ne != np )
   {
      int i;
      PMVectorEdit* edit;
      QLabel* label;
      QPushButton* button;
      QPixmap addPixmap = SmallIcon( "pmaddpoint" );
      QPixmap removePixmap = SmallIcon( "pmremovepoint" );
         
      // recreate the vector edits
      if( m_pEditWidget->layout( ) )
         delete m_pEditWidget->layout( );
         
      m_edits.setAutoDelete( true );
      m_addButtons.setAutoDelete( true );
      m_removeButtons.setAutoDelete( true );
      m_labels.setAutoDelete( true );
      m_edits.clear( );
      m_addButtons.clear( );
      m_removeButtons.clear( );
      m_labels.clear( );
      m_edits.setAutoDelete( false );
      m_addButtons.setAutoDelete( false );
      m_removeButtons.setAutoDelete( false );
      m_labels.setAutoDelete( false );

      QGridLayout* gl = new QGridLayout( m_pEditWidget, np + 1, 4,
                                         0, KDialog::spacingHint( ) );
      button = new QPushButton( m_pEditWidget );
      button->setPixmap( addPixmap );
      m_addButtons.append( button );
      connect( button, SIGNAL( clicked( ) ), SLOT( slotAddPoint( ) ) );
      gl->addWidget( button, 0, 2 );
      button->show( );
      button->setEnabled( !readOnly );
      QToolTip::add( button, i18n( "Add new point" ) );
      
      for( i = 0; i < np; i++ )
      {
         label = new QLabel( QString( "%1:" ).arg( i + 1 ), m_pEditWidget );
         gl->addWidget( label, i+1, 0 );
         label->show( );
         m_labels.append( label );
         
         edit = new PMVectorEdit( "u", "v", m_pEditWidget );
         connect( edit, SIGNAL( dataChanged( ) ), SIGNAL( dataChanged( ) ) );
         m_edits.append( edit );
         gl->addWidget( edit, i+1, 1 );
         edit->show( );
         
         button = new QPushButton( m_pEditWidget );
         button->setPixmap( addPixmap );
         m_addButtons.append( button );
         connect( button, SIGNAL( clicked( ) ), SLOT( slotAddPoint( ) ) );
         gl->addWidget( button, i+1, 2 );
         button->show( );
         QToolTip::add( button, i18n( "Add new point" ) );
         
         button = new QPushButton( m_pEditWidget );
         button->setPixmap( removePixmap );
         m_removeButtons.append( button );
         connect( button, SIGNAL( clicked( ) ), SLOT( slotRemovePoint( ) ) );
         gl->addWidget( button, i+1, 3 );
         button->show( );
         QToolTip::add( button, i18n( "Remove point" ) );
      }
   }
      
   QValueList<PMVector>::ConstIterator pit = sp.begin( );
   QPtrListIterator<PMVectorEdit> eit( m_edits );

   for( ; pit != sp.end( ); ++pit, ++eit )
   {
      eit.current( )->setVector( *pit );
      eit.current( )->setReadOnly( readOnly );
   }

   QPtrListIterator<QPushButton> ait( m_addButtons );
   for( ; ait.current( ); ++ait )
      ait.current( )->setEnabled( !readOnly );
   QPtrListIterator<QPushButton> rit( m_removeButtons );
   for( ; rit.current( ); ++rit )
      rit.current( )->setEnabled( !readOnly );
}

QValueList<PMVector> PMLatheEdit::splinePoints( )
{
   QPtrListIterator<PMVectorEdit> it( m_edits );
   QValueList<PMVector> values;
   
   for( ; it.current( ); ++it )
      values.append( it.current( )->vector( ) );
   
   return values;
}

void PMLatheEdit::saveContents( )
{
   if( m_pDisplayedObject )
   {
      if( !m_edits.isEmpty( ) )
         m_pDisplayedObject->setPoints( splinePoints( ) );

      switch( m_pSplineType->currentItem( ) )
      {
         case 0:
            m_pDisplayedObject->setSplineType( PMLathe::LinearSpline );
            break;
         case 1:
            m_pDisplayedObject->setSplineType( PMLathe::QuadraticSpline );
            break;
         case 2:
            m_pDisplayedObject->setSplineType( PMLathe::CubicSpline );
            break;
         case 3:
            m_pDisplayedObject->setSplineType( PMLathe::BezierSpline );
            break;
      }
      m_pDisplayedObject->setSturm( m_pSturm->isChecked( ) );
      Base::saveContents( );
   }
}

bool PMLatheEdit::isDataValid( )
{
   QPtrListIterator<PMVectorEdit> it( m_edits );
   for( ; it.current( ); ++it )
      if( !it.current( )->isDataValid( ) )
         return false;
   
   int np = m_edits.count( );
   switch( m_pSplineType->currentItem( ) )
   {
      case 0:
         if( np < 2 )
         {
            KMessageBox::error( this, i18n( "Linear splines need at least 2 points." ),
                                i18n( "Error" ) );
            return false;
         }
         break;
      case 1:
         if( np < 3 )
         {
            KMessageBox::error( this, i18n( "Quadratic splines need at least 3 points." ),
                                i18n( "Error" ) );
            return false;
         }
         break;
      case 2:
         if( np < 4 )
         {
            KMessageBox::error( this, i18n( "Cubic splines need at least 4 points." ),
                                i18n( "Error" ) );
            return false;
         }
         break;
      case 3:
         if( ( np < 4 ) || ( ( np % 4 ) != 0 ) )
         {
            KMessageBox::error( this, i18n( "Bezier splines need 4 points for each segment." ),
                                i18n( "Error" ) );
            return false;
         }
         break;
   }
   
   return Base::isDataValid( );
}

void PMLatheEdit::slotTypeChanged( int )
{
   emit dataChanged( );
}

void PMLatheEdit::slotAddPoint( )
{
   QPushButton* button = ( QPushButton* ) sender( );
   if( button )
   {
      int index = m_addButtons.findRef( button );
      if( index >= 0 )
      {
         QValueList<PMVector> points = splinePoints( );
         QValueListIterator<PMVector> it = points.at( index );
         PMVector newPoint( 2 );
         if( index == 0 )
            newPoint = points.first( );
         else
         {
            --it;
            newPoint = *it;
            ++it;
            if( it != points.end( ) )
               newPoint = ( newPoint + *it ) / 2;
         }
         points.insert( it, newPoint );
         displayPoints( points );
         emit dataChanged( );
      }
   }
}

void PMLatheEdit::slotRemovePoint( )
{
   QPushButton* button = ( QPushButton* ) sender( );
   if( button )
   {
      int index = m_removeButtons.findRef( button );
      if( index >= 0 )
      {
         QValueList<PMVector> points = splinePoints( );
         QValueListIterator<PMVector> it = points.at( index );

         if( points.count( ) > 1 )
         {
            points.remove( it );
            displayPoints( points );
            emit dataChanged( );
         }
      }
   }
}

#include "pmlatheedit.moc"
