/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2005-02-14
 * Description : a plugin to insert a text over an image.
 *
 * Copyright (C) 2005-2009 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * Copyright (C) 2006-2009 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.
 *
 * ============================================================ */


#include "inserttexttool.h"
#include "inserttexttool.moc"

// Qt includes

#include <QBrush>
#include <QButtonGroup>
#include <QCheckBox>
#include <QFont>
#include <QFrame>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QPainter>
#include <QPen>
#include <QPixmap>
#include <QTimer>
#include <QToolButton>
#include <QVBoxLayout>

// KDE includes

#include <kaboutdata.h>
#include <kapplication.h>
#include <kcolorbutton.h>
#include <kcombobox.h>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <kcursor.h>
#include <kdebug.h>
#include <kfontchooser.h>
#include <kglobal.h>
#include <khelpmenu.h>
#include <kicon.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmenu.h>
#include <kstandarddirs.h>
#include <ktextedit.h>

// Local includes

#include "daboutdata.h"
#include "dimg.h"
#include "editortoolsettings.h"
#include "imageiface.h"
#include "inserttextwidget.h"
#include "version.h"

using namespace Digikam;

namespace DigikamInsertTextImagesPlugin
{

class InsertTextToolPriv
{
public:

    InsertTextToolPriv()
    {
        alignTextMode     = 0;
        defaultSizeFont   = 0;
        borderText        = 0;
        transparentText   = 0;
        alignButtonGroup  = 0;
        textRotation      = 0;
        fontColorButton   = 0;
        fontChooserWidget = 0;
        textEdit          = 0;
        previewWidget     = 0;
        gboxSettings      = 0;
    }

    int                 alignTextMode;
    int                 defaultSizeFont;

    QCheckBox*          borderText;
    QCheckBox*          transparentText;

    QButtonGroup*       alignButtonGroup;
    QFont               textFont;

    KComboBox*          textRotation;
    KColorButton*       fontColorButton;
    KFontChooser*       fontChooserWidget;
    KTextEdit*          textEdit;

    InsertTextWidget*   previewWidget;
    EditorToolSettings* gboxSettings;
};

InsertTextTool::InsertTextTool(QObject* parent)
              : EditorTool(parent),
                d(new InsertTextToolPriv)
{
    setObjectName("inserttext");
    setToolName(i18n("Insert Text"));
    setToolIcon(SmallIcon("inserttext"));

    // -------------------------------------------------------------

    QFrame *frame = new QFrame(0);
    frame->setFrameStyle(QFrame::Panel|QFrame::Sunken);

    QVBoxLayout* l   = new QVBoxLayout(frame);
    d->previewWidget = new InsertTextWidget(480, 320, frame);
    l->addWidget(d->previewWidget);
    d->previewWidget->setWhatsThis(i18n("This previews the text inserted in the image. "
                                        "You can use the mouse to move the text to the right location."));
    setToolView(frame);

    // -------------------------------------------------------------

    d->gboxSettings = new EditorToolSettings(EditorToolSettings::Default|
                                             EditorToolSettings::Ok|
                                             EditorToolSettings::Cancel);

    // -------------------------------------------------------------

    QGridLayout *grid = new QGridLayout(d->gboxSettings->plainPage());

    d->textEdit = new KTextEdit(d->gboxSettings->plainPage());
    d->textEdit->setCheckSpellingEnabled(true);
    d->textEdit->setWordWrapMode(QTextOption::NoWrap);
    d->textEdit->setWhatsThis( i18n("Here, enter the text you want to insert in your image."));

    // -------------------------------------------------------------

    d->fontChooserWidget = new KFontChooser(d->gboxSettings->plainPage(), KFontChooser::NoDisplayFlags);
    d->fontChooserWidget->setSampleBoxVisible(false);
    d->fontChooserWidget->setWhatsThis(i18n("Here you can choose the font to be used."));

    // -------------------------------------------------------------

    KIconLoader icon;
    QWidget *alignBox   = new QWidget(d->gboxSettings->plainPage());
    QHBoxLayout *hlay   = new QHBoxLayout(alignBox);
    d->alignButtonGroup = new QButtonGroup(alignBox);
    d->alignButtonGroup->setExclusive(true);

    QToolButton *alignLeft = new QToolButton(alignBox);
    d->alignButtonGroup->addButton(alignLeft, ALIGN_LEFT);
    alignLeft->setIcon(SmallIcon("format-justify-left"));
    alignLeft->setCheckable(true);
    alignLeft->setToolTip(i18n("Align text to the left"));

    QToolButton *alignRight = new QToolButton(alignBox);
    d->alignButtonGroup->addButton(alignRight, ALIGN_RIGHT);
    alignRight->setIcon(SmallIcon("format-justify-right"));
    alignRight->setCheckable(true);
    alignRight->setToolTip(i18n("Align text to the right"));

    QToolButton *alignCenter = new QToolButton(alignBox);
    d->alignButtonGroup->addButton(alignCenter, ALIGN_CENTER);
    alignCenter->setIcon(SmallIcon("format-justify-center"));
    alignCenter->setCheckable(true);
    alignCenter->setToolTip(i18n("Align text to center"));

    QToolButton *alignBlock = new QToolButton(alignBox);
    d->alignButtonGroup->addButton(alignBlock, ALIGN_BLOCK);
    alignBlock->setIcon(SmallIcon("format-justify-fill"));
    alignBlock->setCheckable(true);
    alignBlock->setToolTip(i18n("Align text to a block"));

    hlay->setMargin(0);
    hlay->setSpacing(0);
    hlay->addWidget(alignLeft);
    hlay->addWidget(alignRight);
    hlay->addWidget(alignCenter);
    hlay->addWidget(alignBlock);

    // -------------------------------------------------------------

    QLabel *label1 = new QLabel(i18n("Rotation:"), d->gboxSettings->plainPage());
    d->textRotation = new KComboBox(d->gboxSettings->plainPage());
    d->textRotation->addItem(i18nc("no rotation", "None"));
    d->textRotation->addItem(i18n("90 Degrees"));
    d->textRotation->addItem(i18n("180 Degrees"));
    d->textRotation->addItem(i18n("270 Degrees"));
    d->textRotation->setWhatsThis(i18n("Select the text rotation to use here."));

    // -------------------------------------------------------------

    QLabel *label2 = new QLabel(i18nc("font color", "Color:"), d->gboxSettings->plainPage());
    d->fontColorButton = new KColorButton(Qt::black, d->gboxSettings->plainPage());
    d->fontColorButton->setWhatsThis(i18n("Set here the font color to use."));

    // -------------------------------------------------------------

    d->borderText = new QCheckBox(i18n("Add border"), d->gboxSettings->plainPage());
    d->borderText->setToolTip(i18n("Add a solid border around text using current text color"));

    d->transparentText = new QCheckBox(i18n("Semi-transparent"), d->gboxSettings->plainPage());
    d->transparentText->setToolTip(i18n("Use semi-transparent text background under image"));

    // -------------------------------------------------------------

    grid->addWidget(d->textEdit,             0, 0, 3, 2);
    grid->addWidget(d->fontChooserWidget,    3, 0, 1, 2);
    grid->addWidget(alignBox,                4, 0, 1, 2);
    grid->addWidget(label1,                  5, 0, 1, 1);
    grid->addWidget(d->textRotation,         5, 1, 1, 1);
    grid->addWidget(label2,                  6, 0, 1, 1);
    grid->addWidget(d->fontColorButton,      6, 1, 1, 1);
    grid->addWidget(d->borderText,           7, 0, 1, 2);
    grid->addWidget(d->transparentText,      8, 0, 1, 2);
    grid->setRowStretch(9, 10);
    grid->setMargin(d->gboxSettings->spacingHint());
    grid->setSpacing(d->gboxSettings->spacingHint());

    setToolSettings(d->gboxSettings);
    init();

    // -------------------------------------------------------------

    connect(d->fontChooserWidget, SIGNAL(fontSelected(const QFont&)),
            this, SLOT(slotFontPropertiesChanged(const QFont&)));

    connect(d->fontColorButton, SIGNAL(changed(const QColor&)),
            this, SLOT(slotUpdatePreview()));

    connect(d->textEdit, SIGNAL(textChanged()),
            this, SLOT(slotUpdatePreview()));

    connect(d->alignButtonGroup, SIGNAL(buttonReleased(int)),
            this, SLOT(slotAlignModeChanged(int)));

    connect(d->borderText, SIGNAL(toggled(bool)),
            this, SLOT(slotUpdatePreview()));

    connect(d->transparentText, SIGNAL(toggled(bool)),
            this, SLOT(slotUpdatePreview()));

    connect(d->textRotation, SIGNAL(activated(int)),
            this, SLOT(slotUpdatePreview()));

    connect(this, SIGNAL(signalUpdatePreview()),
            this, SLOT(slotUpdatePreview()));

    // -------------------------------------------------------------

    slotUpdatePreview();
}

InsertTextTool::~InsertTextTool()
{
    delete d;
}

void InsertTextTool::readSettings()
{
    KSharedConfig::Ptr config = KGlobal::config();
    KConfigGroup group =  config->group("inserttext Tool");
    QColor black(0, 0, 0);
    QFont  defaultFont;

    int orgW = d->previewWidget->imageIface()->originalWidth();
    int orgH = d->previewWidget->imageIface()->originalHeight();

    if ( orgW > orgH ) d->defaultSizeFont = (int)(orgH / 8.0);
    else d->defaultSizeFont = (int)(orgW / 8.0);

    defaultFont.setPointSize(d->defaultSizeFont);
    d->textRotation->setCurrentIndex(group.readEntry("Text Rotation", 0));
    d->fontColorButton->setColor(group.readEntry("Font Color", black));
    d->textEdit->setText(group.readEntry("Text String", i18n("Enter your text here.")));
    d->textFont = group.readEntry("Font Properties", defaultFont);
    d->fontChooserWidget->setFont(d->textFont);
    d->alignTextMode = group.readEntry("Text Alignment", (int) ALIGN_LEFT);
    d->borderText->setChecked(group.readEntry("Border Text", false));
    d->transparentText->setChecked(group.readEntry("Transparent Text", false));
    d->previewWidget->setPositionHint(group.readEntry("Position Hint", QRect()));

    d->alignButtonGroup->button(d->alignTextMode)->setChecked(true);
    slotAlignModeChanged(d->alignTextMode);
}

void InsertTextTool::writeSettings()
{
    KSharedConfig::Ptr config = KGlobal::config();
    KConfigGroup group = config->group("inserttext Tool");

    group.writeEntry("Text Rotation", d->textRotation->currentIndex());
    group.writeEntry("Font Color", d->fontColorButton->color());
    group.writeEntry("Text String", d->textEdit->document()->toPlainText());
    group.writeEntry("Font Properties", d->textFont);
    group.writeEntry("Text Alignment", d->alignTextMode);
    group.writeEntry("Border Text", d->borderText->isChecked());
    group.writeEntry("Transparent Text", d->transparentText->isChecked());
    group.writeEntry("Position Hint", d->previewWidget->getPositionHint());

    config->sync();
}

void InsertTextTool::slotResetSettings()
{
    d->fontColorButton->blockSignals(true);
    d->alignButtonGroup->blockSignals(true);
    d->fontChooserWidget->blockSignals(true);

    d->textRotation->setCurrentIndex(0); // No rotation.
    d->fontColorButton->setColor(Qt::black);
    QFont defaultFont;
    d->textFont = defaultFont; // Reset to default KDE font.
    d->textFont.setPointSize(d->defaultSizeFont);
    d->fontChooserWidget->setFont(d->textFont);
    d->borderText->setChecked(false);
    d->transparentText->setChecked(false);
    d->previewWidget->resetEdit();
    d->alignButtonGroup->button(ALIGN_LEFT)->setChecked(true);

    d->fontChooserWidget->blockSignals(false);
    d->fontColorButton->blockSignals(false);
    d->alignButtonGroup->blockSignals(false);
    slotAlignModeChanged(ALIGN_LEFT);
}

void InsertTextTool::slotAlignModeChanged(int mode)
{
    d->alignTextMode = mode;
    d->textEdit->selectAll();

    switch (d->alignTextMode)
    {
        case ALIGN_LEFT:
            d->textEdit->setAlignment(Qt::AlignLeft);
            break;

        case ALIGN_RIGHT:
            d->textEdit->setAlignment(Qt::AlignRight);
            break;

        case ALIGN_CENTER:
            d->textEdit->setAlignment(Qt::AlignHCenter);
            break;

        case ALIGN_BLOCK:
            d->textEdit->setAlignment(Qt::AlignJustify);
            break;
    }

    d->textEdit->textCursor().clearSelection();
    emit signalUpdatePreview();
}

void InsertTextTool::slotFontPropertiesChanged(const QFont& font)
{
    d->textFont = font;
    emit signalUpdatePreview();
}

void InsertTextTool::slotUpdatePreview()
{
    d->previewWidget->setText(d->textEdit->document()->toPlainText(), d->textFont, d->fontColorButton->color(), d->alignTextMode,
                             d->borderText->isChecked(), d->transparentText->isChecked(),
                             d->textRotation->currentIndex());
}

void InsertTextTool::finalRendering()
{
    kapp->setOverrideCursor( Qt::WaitCursor );

    ImageIface iface(0, 0);
    DImg dest = d->previewWidget->makeInsertText();
    iface.putOriginalImage(i18n("Insert Text"), dest.bits(), dest.width(), dest.height());

    kapp->restoreOverrideCursor();
}

}  // namespace DigikamInsertTextImagesPlugin
