/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2005-01-04
 * Description : a Digikam image editor plugin for superimpose a 
 *               template to an image.
 *
 * Copyright (C) 2005-2008 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * Copyright (C) 2006-2008 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 *
 * 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, 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.
 *
 * ============================================================ */

// TQt includes. 
 
#include <tqvgroupbox.h>
#include <tqgroupbox.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqpixmap.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>
#include <tqlayout.h>
#include <tqframe.h>
#include <tqdir.h>
#include <tqfile.h>
#include <tqhbuttongroup.h> 

// KDE includes.

#include <kcursor.h>
#include <tdelocale.h>
#include <tdeaboutdata.h>
#include <khelpmenu.h>
#include <kiconloader.h>
#include <tdeapplication.h>
#include <tdepopupmenu.h>
#include <kstandarddirs.h>
#include <kprogress.h>
#include <knuminput.h>
#include <kiconloader.h>
#include <tdefiledialog.h> 
#include <tdeapplication.h>
#include <tdeconfig.h>
#include <tdeglobalsettings.h>

// Local includes.

#include "version.h"
#include "ddebug.h"
#include "dimg.h"
#include "imageiface.h"
#include "thumbbar.h"
#include "superimposewidget.h"
#include "dirselectwidget.h"
#include "imageeffect_superimpose.h"
#include "imageeffect_superimpose.moc"

namespace DigikamSuperImposeImagesPlugin
{

ImageEffect_SuperImpose::ImageEffect_SuperImpose(TQWidget* parent)
                       : Digikam::ImageDlgBase(parent, i18n("Template Superimpose to Photograph"),
                                               "superimpose", false, false)
{
    TQString whatsThis;
           
    // About data and help button.
    
    TDEAboutData* about = new TDEAboutData("digikam",
                                       I18N_NOOP("Template Superimpose"), 
                                       digikam_version,
                                       I18N_NOOP("A digiKam image plugin to superimpose a template onto a photograph."),
                                       TDEAboutData::License_GPL,
                                       "(c) 2005-2006, Gilles Caulier\n"
                                       "(c) 2006-2008, Gilles Caulier and Marcel Wiesweg", 
                                       0,
                                       "http://www.digikam.org");
    
    about->addAuthor("Gilles Caulier", I18N_NOOP("Author and maintainer"),
                     "caulier dot gilles at gmail dot com");
    
    about->addAuthor("Marcel Wiesweg", I18N_NOOP("Developer"),
                     "marcel dot wiesweg at gmx dot de");

    setAboutData(about);    
    
    // -------------------------------------------------------------
    
    TQFrame *frame = new TQFrame(plainPage());
    frame->setFrameStyle(TQFrame::Panel|TQFrame::Sunken);

    TQGridLayout* gridFrame = new TQGridLayout( frame, 1, 2, spacingHint());
    m_previewWidget        = new SuperImposeWidget(400, 300, frame);
    gridFrame->addMultiCellWidget(m_previewWidget, 0, 0, 0, 2);
    gridFrame->setRowStretch(0, 10);
    TQWhatsThis::add( m_previewWidget, i18n("<p>This is the preview of the template "
                                           "superimposed onto the image.") );
    
    // -------------------------------------------------------------

    TQHButtonGroup *bGroup = new TQHButtonGroup(frame);
    TDEIconLoader icon;
    bGroup->addSpace(0);
    TQPushButton *zoomInButton = new TQPushButton( bGroup );
    bGroup->insert(zoomInButton, ZOOMIN);
    zoomInButton->setPixmap( icon.loadIcon( "zoom-in", (TDEIcon::Group)TDEIcon::Toolbar ) );
    zoomInButton->setToggleButton(true);
    TQToolTip::add( zoomInButton, i18n( "Zoom in" ) );
    bGroup->addSpace(20);
    TQPushButton *zoomOutButton = new TQPushButton( bGroup );
    bGroup->insert(zoomOutButton, ZOOMOUT);
    zoomOutButton->setPixmap( icon.loadIcon( "zoom-out", (TDEIcon::Group)TDEIcon::Toolbar ) );
    zoomOutButton->setToggleButton(true);
    TQToolTip::add( zoomOutButton, i18n( "Zoom out" ) );
    bGroup->addSpace(20);
    TQPushButton *moveButton = new TQPushButton( bGroup );
    bGroup->insert(moveButton, MOVE);
    moveButton->setPixmap( icon.loadIcon( "move", (TDEIcon::Group)TDEIcon::Toolbar ) );
    moveButton->setToggleButton(true);
    moveButton->setOn(true);
    TQToolTip::add( moveButton, i18n( "Move" ) );
    bGroup->addSpace(20);
    bGroup->setExclusive(true);
    bGroup->setFrameShape(TQFrame::NoFrame);
    gridFrame->addMultiCellWidget(bGroup, 1, 1, 1, 1);
    gridFrame->setColStretch(0, 10);
    gridFrame->setColStretch(2, 10);
    
    setPreviewAreaWidget(frame);     
    
    // -------------------------------------------------------------
    
    TQWidget *gbox2    = new TQWidget(plainPage());
    TQGridLayout* grid = new TQGridLayout( gbox2, 1, 1, marginHint(), spacingHint());
    
    m_thumbnailsBar = new Digikam::ThumbBarView(gbox2);
    m_dirSelect     = new DirSelectWidget(gbox2);
    TQPushButton *templateDirButton = new TQPushButton( i18n("Root Directory..."), gbox2 );
    TQWhatsThis::add( templateDirButton, i18n("<p>Set here the current templates' root directory.") );

    grid->addMultiCellWidget(m_thumbnailsBar, 0, 1, 0, 0);
    grid->addMultiCellWidget(m_dirSelect, 0, 0, 1, 1);    
    grid->addMultiCellWidget(templateDirButton, 1, 1, 1, 1);    
    grid->setColStretch(1, 10);

    setUserAreaWidget(gbox2);
    
    // -------------------------------------------------------------
    
    connect(bGroup, TQ_SIGNAL(released(int)),
            m_previewWidget, TQ_SLOT(slotEditModeChanged(int)));
    
    connect(m_thumbnailsBar, TQ_SIGNAL(signalURLSelected(const KURL&)),
            m_previewWidget, TQ_SLOT(slotSetCurrentTemplate(const KURL&)));            

    connect(m_dirSelect, TQ_SIGNAL(folderItemSelected(const KURL &)),
            this, TQ_SLOT(slotTemplateDirChanged(const KURL &)));
    
    connect(templateDirButton, TQ_SIGNAL(clicked()),
            this, TQ_SLOT(slotRootTemplateDirChanged()));
                                    
    // -------------------------------------------------------------
    
    populateTemplates();
}

ImageEffect_SuperImpose::~ImageEffect_SuperImpose()
{
}

void ImageEffect_SuperImpose::populateTemplates(void)
{
    m_thumbnailsBar->clear(true);
    
    if (!m_templatesUrl.isValid() || !m_templatesUrl.isLocalFile())
       return;
       
    TQDir dir(m_templatesUrl.path(), "*.png *.PNG");
    
    if (!dir.exists())
       return;
       
    dir.setFilter ( TQDir::Files | TQDir::NoSymLinks );

    const TQFileInfoList* fileinfolist = dir.entryInfoList();
    if (!fileinfolist)
       return;
    
    TQFileInfoListIterator it(*fileinfolist);
    TQFileInfo* fi;

    while( (fi = it.current() ) )
    {
        new Digikam::ThumbBarItem( m_thumbnailsBar, KURL(fi->filePath()) );
        ++it;
    }
}

void ImageEffect_SuperImpose::readUserSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("Album Settings");
    KURL albumDBUrl( config->readPathEntry("Album Path", TDEGlobalSettings::documentPath()) );
    config->setGroup("superimpose Tool Dialog");
    config->setGroup("Template Superimpose Tool Settings");
    m_templatesRootUrl.setPath( config->readEntry("Templates Root URL", albumDBUrl.path()) );
    m_templatesUrl.setPath( config->readEntry("Templates URL", albumDBUrl.path()) );
    m_dirSelect->setRootPath(m_templatesRootUrl, m_templatesUrl);
}

void ImageEffect_SuperImpose::writeUserSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("superimpose Tool Dialog");
    config->writeEntry( "Templates Root URL", m_dirSelect->rootPath().path() );
    config->writeEntry( "Templates URL", m_templatesUrl.path() );
    config->sync();}

void ImageEffect_SuperImpose::resetValues()
{
    m_previewWidget->resetEdit();
} 

void ImageEffect_SuperImpose::slotRootTemplateDirChanged(void)
{
    KURL url = KFileDialog::getExistingDirectory(m_templatesRootUrl.path(), kapp->activeWindow(),
                                                 i18n("Select Template Root Directory to Use"));

    if( url.isValid() )
    {
        m_dirSelect->setRootPath(url);
        m_templatesRootUrl = url;
        m_templatesUrl = url;
        populateTemplates();
    }
}

void ImageEffect_SuperImpose::slotTemplateDirChanged(const KURL& url)
{
    if( url.isValid() )
    {
        m_templatesUrl = url;
        populateTemplates();
    }
}

void ImageEffect_SuperImpose::finalRendering()
{
    setCursor(KCursor::waitCursor());
    m_previewWidget->setEnabled(false);
    m_dirSelect->setEnabled(false);
    m_thumbnailsBar->setEnabled(false);

    Digikam::ImageIface iface(0, 0);
    Digikam::DImg img = m_previewWidget->makeSuperImpose();
    iface.putOriginalImage(i18n("Super Impose"), img.bits(),
                           img.width(), img.height() );

    m_previewWidget->setEnabled(true);
    m_dirSelect->setEnabled(true);
    m_thumbnailsBar->setEnabled(true);
    unsetCursor();
    accept();
}

}  // NameSpace DigikamSuperImposeImagesPlugin

