/*
 * Copyright 2010 Mihai Niculescu <q.quark@gmail.com>
 *
 * This file is part of EqualX Project (https://launchpad.net/equalx/)
 *
 * EqualX 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 3 of the License, or
 * (at your option) any later version.
 *
 * EqualX 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, see <http://www.gnu.org/licenses/>.
 */

#include <QButtonGroup>
#include <QFileDialog>

#include "defines.h"
#include "DialogPreferences.h"
#include "Library/Library.h"

DialogPreferences::DialogPreferences(QWidget *parent)
    : QDialog(parent)
{
    setupUi(this);

    setupPreferencesListWidget();

    connect(browsePDFLatex, SIGNAL(released()), this, SLOT(onBrowsePdfLatex()) );
    connect(browsePDFtoCairo, SIGNAL(released()), this, SLOT(onBrowsePdfToCairo()) );
    connect(browseGS, SIGNAL(released()), this, SLOT(onBrowseGS()) );
    connect(buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(onClickedButtonBox(QAbstractButton*))  );

    renderModeButtonGroup = new QButtonGroup;
    renderModeButtonGroup->addButton(renderModeDisplay, LATEX_ENV_MODE_DISPLAY);
    renderModeButtonGroup->addButton(renderModeInline, LATEX_ENV_MODE_INLINE);
    renderModeButtonGroup->addButton(renderModeAlign, LATEX_ENV_MODE_ALIGN);
    renderModeButtonGroup->addButton(renderModeText, LATEX_ENV_MODE_TEXT);

    connect(clearHistoryButton, SIGNAL(clicked()), LibraryManager::Instance(), SLOT(clearHistory()) );
}

DialogPreferences::~DialogPreferences()
{
    delete renderModeButtonGroup;
}

const QFont DialogPreferences::getFont() const
{
    QFont font;
    font.setFamily(comboFontFamily->currentText());
    font.setPointSize(comboFontSize->currentText().toInt());

    return font;

}

int DialogPreferences::renderMode() const
{
    return renderModeButtonGroup->checkedId();
}

QString DialogPreferences::currentExportType() const
{
    return exportCBox->currentText();
}

void DialogPreferences::setCurrentExportType(const QString &fileType)
{
    int idx = exportCBox->findText(fileType,Qt::MatchExactly);
    exportCBox->setCurrentIndex(idx);
}

void DialogPreferences::setCurrentExportType(QAction *actionType)
{
    setCurrentExportType(actionType->data().toString());
}

void DialogPreferences::setCurrentFont(const QString &fontDescription)
{
    QStringList fontDescList = fontDescription.split(",");
    QString fontFamily = fontDescList.at(0);
    int idx = comboFontFamily->findText(fontFamily, Qt::MatchExactly);
    comboFontFamily->setCurrentIndex(idx);

    QString size = fontDescList.at(1);
    idx = comboFontSize->findText(size, Qt::MatchExactly);
    comboFontSize->setCurrentIndex(idx);
}

void DialogPreferences::onClickedButtonBox(QAbstractButton *b)
{
    if(buttonBox->button(QDialogButtonBox::RestoreDefaults)==b) resetDefaults();
}

void DialogPreferences::onBrowsePdfLatex()
{
    QString filePath = QFileDialog::getOpenFileName(this,
                                                    tr("Select Executable (pdflatex)"), QDir::homePath(), "pdflatex (*.exe, .*)");
    if(!filePath.isEmpty())
        pdfLatexEdit->setText(filePath);
}

void DialogPreferences::onBrowsePdfToCairo()
{
    QString filePath = QFileDialog::getOpenFileName(this,
                                                    tr("Select Executable (pdftocairo)"), QDir::homePath(), "pdftocairo (*.exe, .*)");
    if(!filePath.isEmpty())
        pdfCairoEdit->setText(filePath);
}

void DialogPreferences::onBrowseGS()
{
    QString filePath = QFileDialog::getOpenFileName(this,
                                                    tr("Select Executable (gs)"), QDir::homePath(), "gs (*.exe, .*)");
    if(!filePath.isEmpty())
        gsEdit->setText(filePath);
}

void DialogPreferences::resetDefaults()
{
    // GENERAL
    checkRememberLayout->setChecked( DEFAULT_REMEMBER_LAYOUT );

    int idx = exportCBox->findData(DEFAULT_EXPORT_TYPE, Qt::UserRole, Qt::MatchExactly);
    exportCBox->setCurrentIndex(idx);

    // EDITOR
    QFont font(DEFAULT_FONT, DEFAULT_FONT_SIZE);
    comboFontFamily->setCurrentFont( font );
    comboFontSize->setCurrentIndex( DEFAULT_FONT_SIZE );
    checkSyntaxHighligthing->setChecked( DEFAULT_HIGHLIGHTING );
    checkTextWrapping->setChecked( DEFAULT_WRAPPING );
    groupBoxCompletion->setChecked( DEFAULT_COMPLETION );
    checkSensitiveCompletion->setChecked( DEFAULT_COMPLETION );

    // PREVIEW
    renderAutoUpdate->setChecked( DEFAULT_UPDATE_AUTO );
    renderManualUpdate->setChecked( DEFAULT_UPDATE_AUTO );
    spinUpdateTime->setValue(DEFAULT_UPDATE_TIME );
    bgPreviewColor->setColorName(DEFAULT_PREVIEW_BG);
    // Equation
    fgColorPicker->setColorName( DEFAULT_RENDER_FG );
    bgColorPicker->setColorName( DEFAULT_RENDER_BG );
    renderFontSize->setCurrentIndex( DEFAULT_RENDER_FONT_SIZE );

    switch(DEFAULT_RENDER_MODE){
    case LATEX_ENV_MODE_INLINE:
        renderModeInline->setChecked(true);
        break;
    case LATEX_ENV_MODE_ALIGN:
        renderModeAlign->setChecked(true);
        break;
    case LATEX_ENV_MODE_TEXT:
        renderModeText->setChecked(true);
        break;
    default:
    case LATEX_ENV_MODE_DISPLAY:
        renderModeDisplay->setChecked(true);
        break;
    }

    // COMMANDS
    pdfLatexEdit->setText( DEFAULT_PDFLATEX );
    pdfCairoEdit->setText( DEFAULT_PDFCAIRO );
    gsEdit->setText( DEFAULT_GS);
}

void DialogPreferences::setupPreferencesListWidget()
{
    preferencesListWidget->setViewMode(QListView::IconMode);
    preferencesListWidget->setFlow(QListView::TopToBottom);
    preferencesListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    preferencesListWidget->setIconSize(QSize(32,32));
    preferencesListWidget->setSpacing(0);
    preferencesListWidget->setDragEnabled(false);
    preferencesListWidget->setSelectionRectVisible(false);
    preferencesListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    preferencesListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);


    QListWidgetItem* item = new QListWidgetItem(QIcon("://resources/icons/preferences/general.png"), tr("General"), preferencesListWidget);
    item->setData(Qt::UserRole+1, ITEM_GENERAL);
    preferencesListWidget->setCurrentItem(item);

    item = new QListWidgetItem(QIcon("://resources/icons/preferences/editor.png"), tr("Editor"), preferencesListWidget);
    item->setData(Qt::UserRole+1, ITEM_EDITOR);

    item = new QListWidgetItem(QIcon("://resources/icons/preferences/preview.png"), tr("Preview"), preferencesListWidget);
    item->setData(Qt::UserRole+1, ITEM_PREVIEW);

    item = new QListWidgetItem(QIcon("://resources/icons/preferences/advanced.png"), tr("Advanced"), preferencesListWidget);
    item->setData(Qt::UserRole+1, ITEM_ADVANCED);


    //QRect r = preferencesListWidget->visualItemRect(item);
    preferencesListWidget->setMaximumHeight(preferencesListWidget->sizeHintForRow(0)+2);


    connect(preferencesListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onPreferencesItemActivated(QListWidgetItem*)) );
}

void DialogPreferences::onPreferencesItemActivated(QListWidgetItem *item)
{
    stackedWidget->setCurrentIndex(item->data(Qt::UserRole+1).toInt());
}
