/***************************************************************************
 *   Copyright (C) 2003 by Yann Bouan                                      *
 *   <yann@bouan.net>                                                      *
 *                                                                         *
 *   Copyright (C) 2003 by Claudio J. Chiabai                              *
 *   <chiabai@users.sourceforge.net>                                       *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   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 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.             *
 ***************************************************************************/

// archivos include para Qt
#include <qlayout.h>
#include <qpushbutton.h>

// archivos include para KDE
#include <klocale.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>

// archivos include para app
#include "picwiz.h"

/****************************************************************************************
 * Constructor / Destructor                                                             *
 ****************************************************************************************/

PicWiz::PicWiz()
    : KWizard( 0, "PicWiz" )
{
  setupPage1();
  setupPage2();
  cancelButton()->setText(i18n("&Close"));
  m_img = new QImage();
  changeMode();

  connect(this, SIGNAL(selected(const QString &)), this, SLOT(resize(const QString &)));
  connect(this, SIGNAL(helpClicked()), this, SLOT(about()));
}

PicWiz::~PicWiz()
{
  kapp->config()->writeEntry("Standard size", m_standardSize->isChecked());
  kapp->config()->writeEntry("Size entry", m_sizeCombo->currentItem());
  kapp->config()->writeEntry("Custom size", m_customSize->isChecked());
  kapp->config()->writeEntry("Custom height", m_height->value());
  kapp->config()->writeEntry("Custom width", m_width->value());
  kapp->config()->writeEntry("Overwrite file", m_overwrite->isChecked());
  kapp->config()->sync();
}

/****************************************************************************************
 * Page 1 - Size chooser                                                                *
 ****************************************************************************************/
void PicWiz::setupPage1()
{
  // Page 1 =====================================================
  page1 = new QButtonGroup( this );
  //page1->setGeometry( QRect( 0, 10, 199, 225 ) );
  page1->setRadioButtonExclusive( true );
  page1->setFrameShape( QButtonGroup::NoFrame );
  page1->setColumnLayout(0, Qt::Vertical );
  page1->layout()->setSpacing( 6 );
  page1->layout()->setMargin( 11 );
  QVBoxLayout* lyt = new QVBoxLayout( page1->layout() );
  lyt->setAlignment( Qt::AlignTop );

  // Standard Size ===============================================
  m_standardSize = new QRadioButton(i18n("Standard size"), page1);
  m_standardSize->setChecked(kapp->config()->readBoolEntry("Standard size", true));
  connect(m_standardSize, SIGNAL(clicked()), SLOT(changeMode()));
  lyt->addWidget(m_standardSize);

  // Combo -----------------------------------------------
  m_sizeCombo = new KComboBox(page1);
  // Icon size's
  m_sizeCombo->insertItem(i18n("Small Icon %1").arg("(16x16)"));
  m_sizeCombo->insertItem(i18n("Small Icon %1").arg("(22x22)"));
  m_sizeCombo->insertItem(i18n("Medium Icon %1").arg("(32x32)"));
  m_sizeCombo->insertItem(i18n("Large Icon %1").arg("(48x48)"));
  // image size's
  m_sizeCombo->insertItem(i18n("PDA %1").arg("(80x60)"));
  m_sizeCombo->insertItem(i18n("Tiny %1").arg("(320x240)"));
  m_sizeCombo->insertItem(i18n("Small %1").arg("(640x480)"));
  m_sizeCombo->insertItem(i18n("Small %1").arg("(720x540)"));
  m_sizeCombo->insertItem(i18n("Medium %1").arg("(800x600)"));
  m_sizeCombo->insertItem(i18n("Normal %1").arg("(1024x768)"));
  m_sizeCombo->insertItem(i18n("Big %1").arg("(1280x960)"));
  m_sizeCombo->insertItem(i18n("Huge %1").arg("(1600x1200)"));

  // Default size ------------------------------------
  m_sizeCombo->setCurrentItem(kapp->config()->readUnsignedLongNumEntry("Size entry", 6)); // 640x480

  // Connect -------------------------------
  connect(m_sizeCombo, SIGNAL(activated(int)), this, SLOT(sizeSelection(int)));

  lyt->addWidget(m_sizeCombo);

  // Custom Size =================================================
  m_customSize = new QRadioButton(i18n("Custom size"), page1);
  m_customSize->setChecked(kapp->config()->readBoolEntry("Custom size", false));
  connect(m_customSize, SIGNAL(clicked()), SLOT(changeMode()));
  lyt->addWidget(m_customSize);

  // Height --------------------------------------------------
  QHBoxLayout* lyt2 = new QHBoxLayout( 0, 0, 0);
  lblHeight = new QLabel(i18n("Height :"), page1 );
  lyt2->addWidget(lblHeight );

  int value = kapp->config()->readUnsignedNumEntry("Custom height", 640);
  m_height = new KIntNumInput(value, page1);
  m_height->setRange (1, 10000, 10, false);
  lyt2->addWidget( m_height );

  lyt->addLayout( lyt2 );

  // Width --------------------------------------------------
  lyt2 = new QHBoxLayout( 0, 0, 0);
  lblWidth = new QLabel(i18n("Width :"), page1);
  lyt2->addWidget(lblWidth );

  value = kapp->config()->readUnsignedNumEntry("Custom width", 480);
  m_width = new KIntNumInput(value, page1);
  m_width->setRange(1, 10000, 10, false);
  lyt2->addWidget( m_width );

  lyt->addLayout( lyt2 );

  // Overwrite file ==============================================
  /* YB added checkbox for overwriting (04-23-2003))*/
  m_overwrite = new QCheckBox(i18n("Overwrite file"), page1);
  m_overwrite->setChecked(kapp->config()->readBoolEntry("Overwrite file", false));
  lyt->addWidget(m_overwrite);

  // Spacer ======================================================
  lyt->addItem(new QSpacerItem( 2, 2, QSizePolicy::Minimum, QSizePolicy::Expanding ));

  // Add page ========================================================
  addPage(page1, i18n("Choose the new size"));
  setHelpEnabled(page1, true);
  setBackEnabled(page1, false);
  setNextEnabled(page1, true);
}

void PicWiz::changeMode()
{
  // Standard ===============================
  m_sizeCombo->setEnabled(m_standardSize->isChecked());

  if (m_standardSize->isChecked())
    sizeSelection(m_sizeCombo->currentItem());

  // Custom =================================
  lblHeight->setEnabled(m_customSize->isChecked());
  lblWidth->setEnabled(m_customSize->isChecked());
  m_height->setEnabled(m_customSize->isChecked());
  m_width->setEnabled(m_customSize->isChecked());

  if(m_customSize->isChecked())
  {
    height = m_height->value();
    width  = m_width->value();
  }
}

void PicWiz::sizeSelection(int id)
{
  // Icon size's ---------------------------------
  if (id == 0)  { height =   16; width =   16; }
  if (id == 1)  { height =   22; width =   22; }
  if (id == 2)  { height =   32; width =   32; }
  if (id == 3)  { height =   48; width =   48; }
  // Image size's ---------------------------------
  if (id == 4)  { height =   80; width =   60; }
  if (id == 5)  { height =  320; width =  240; }
  if (id == 6)  { height =  640; width =  480; }
  if (id == 7)  { height =  720; width =  540; }
  if (id == 8)  { height =  800; width =  600; }
  if (id == 9)  { height = 1024; width =  768; }
  if (id == 10) { height = 1280; width =  960; }
  if (id == 11) { height = 1600; width = 1200; }
}

/****************************************************************************************
 * Page 2 - Finished message                                                            *
 ****************************************************************************************/

void PicWiz::setupPage2()
{
  // Page 1 =====================================================
  page2 = new QVBox(this);
  m_results = new KListBox(page2);
  m_progress = new KProgress(page2);

  // Add page ========================================================
  addPage(page2, i18n("Processed files"));
  setHelpEnabled(page2, true);
  setBackEnabled(page2, true);
  setNextEnabled(page2, false);
}

/*
* resize processes each image file in the argument line and resizes it.
*/
void PicWiz::resize(const QString &titlePage)
{
  if (titlePage == title(page2))
  {
    // inicialization ---------------------------------
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // Command arguments
    setFinishEnabled(page2, false);
    setBackEnabled(page2, false);

    // Progress bar --------------
    m_progress->setValue(0);
    m_progress->setRange(0, args->count());
    m_progress->setFormat(i18n("%v of %m (%p %)")); // 1 of 34 ( 5%) <-- example


    for ( int i = 0; i <= args->count() - 1; i++ )
    {
      QString filePath = args->url(i).path();
      m_progress->setValue(i+1);

      kdDebug() << "Procesing " << filePath << "..." << endl;
      m_results->insertItem( filePath + " " + i18n("(Procesing ...)"));
      kapp->processEvents();

    // Resize ==================================================

      if (m_img->load( filePath ))
      {

        // Resize -------------------------------------------------
        if(m_img->width() > m_img->height())
          *m_img = m_img->smoothScale(width, height, QImage::ScaleMin);
        else
          *m_img = m_img->smoothScale(height, width, QImage::ScaleMin);


        QString outputPath = filePath;
        /* YB added renaming capabilities (04-23-2003))*/
        if (!m_overwrite->isChecked())
        {
           outputPath.insert( outputPath.findRev('.'), "-" + QString("%1x%1").arg(height).arg(width) );
        }

        // Save ---------------------------------------------
        if (!m_img->save(outputPath, m_img->imageFormat(filePath)))
        {
          m_results->changeItem(filePath + " " + i18n("( Error : Could not save )"), m_results->count() -1  );
        }
        else
          m_results->changeItem(filePath + " " + i18n("( Ok )"), m_results->count() -1  );
      }
      else
      { // No read message -----------------------
          m_results->changeItem(filePath + " " + i18n("( Error : No read permissions? )"), m_results->count() -1  );
      }
      kapp->processEvents();
    }
    setFinishEnabled(page2, true);
  }
}

void PicWiz::about()
{
}


#include "picwiz.moc"
