KexiCSVExportWizard::KexiCSVExportWizard(const KexiCSVExport::Options& options,
        QWidget * parent)
        : KAssistantDialog(parent)
        , m_options(options)
// , m_mode(mode)
// , m_itemId(itemId)
        , m_fileSavePage(0)
        , m_defaultsBtn(0)
        , m_importExportGroup(KGlobal::config()->group("ImportExport"))
        , m_cancelled(false)
{
    if (m_options.mode == KexiCSVExport::Clipboard) {
        button(KDialog::User1)->setText(i18n("Copy"));
    } else {
        button(KDialog::User1)->setText(i18n("Export"));
    }
    showButton(KDialog::Help, false);

    QString infoLblFromText;
    KexiGUIMessageHandler msgh(this);
    m_tableOrQuery = new KexiDB::TableOrQuerySchema(
        KexiMainWindowIface::global()->project()->dbConnection(), m_options.itemId);
    if (m_tableOrQuery->table()) {
        if (m_options.mode == KexiCSVExport::Clipboard) {
            setWindowTitle(i18n("Copy Data From Table to Clipboard"));
            infoLblFromText = i18n("Copying data from table:");
        } else {
            setWindowTitle(i18n("Export Data From Table to CSV File"));
            infoLblFromText = i18n("Exporting data from table:");
        }
    } else if (m_tableOrQuery->query()) {
        if (m_options.mode == KexiCSVExport::Clipboard) {
            setWindowTitle(i18n("Copy Data From Query to Clipboard"));
            infoLblFromText = i18n("Copying data from table:");
        } else {
            setWindowTitle(i18n("Export Data From Query to CSV File"));
            infoLblFromText = i18n("Exporting data from query:");
        }
    } else {
        msgh.showErrorMessage(KexiMainWindowIface::global()->project()->dbConnection(),
                              i18n("Could not open data for exporting."));
        m_cancelled = true;
        return;
    }

    QString text = "\n" + m_tableOrQuery->captionOrName();
    int m_rowCount = KexiDB::rowCount(*m_tableOrQuery);
    int columns = KexiDB::fieldCount(*m_tableOrQuery);
    text += "\n";
    if (m_rowCount > 0)
        text += i18n("(rows: %1, columns: %2)", m_rowCount, columns);
    else
        text += i18n("(columns: %1)", columns);
    infoLblFromText.append(text);

    // OK, source data found.

    // Setup pages

    // 1. File Save Page
    if (m_options.mode == KexiCSVExport::File) {
        m_fileSaveWidget = new KexiFileWidget(
            KUrl("kfiledialog:///CSVImportExport"), //startDir
            KexiFileWidget::Custom | KexiFileWidget::SavingFileBasedDB,
            this);
        m_fileSaveWidget->setObjectName("m_fileSavePage");
        //m_fileSavePage->setMinimumHeight(kapp->desktop()->availableGeometry().height() / 2);
        m_fileSaveWidget->setAdditionalFilters(csvMimeTypes().toSet());
        m_fileSaveWidget->setDefaultExtension("csv");
        m_fileSaveWidget->setLocationText(
            KexiUtils::stringToFileName(m_tableOrQuery->captionOrName()));
        m_fileSavePage = new KPageWidgetItem(m_fileSaveWidget, i18n("Enter Name of File You Want to Save Data To"));
        addPage(m_fileSavePage);
        connect(this, SIGNAL(currentPageChanged(KPageWidgetItem*,KPageWidgetItem*)),
                this, SLOT(slotCurrentPageChanged(KPageWidgetItem*,KPageWidgetItem*)));
    }
KexiCSVExportWizard::KexiCSVExportWizard(const KexiCSVExport::Options& options,
        QWidget * parent)
        : K3Wizard(parent)
        , m_options(options)
// , m_mode(mode)
// , m_itemId(itemId)
        , m_fileSavePage(0)
        , m_defaultsBtn(0)
        , m_importExportGroup(KGlobal::config()->group("ImportExport"))
        , m_rowCount(-1)
        , m_rowCountDetermined(false)
        , m_cancelled(false)
{
    if (m_options.mode == KexiCSVExport::Clipboard) {
        finishButton()->setText(i18n("Copy"));
        backButton()->hide();
    } else {
        finishButton()->setText(i18n("Export"));
    }
    helpButton()->hide();

    QString infoLblFromText;
    KexiGUIMessageHandler msgh(this);
    m_tableOrQuery = new KexiDB::TableOrQuerySchema(
        KexiMainWindowIface::global()->project()->dbConnection(), m_options.itemId);
    if (m_tableOrQuery->table()) {
        if (m_options.mode == KexiCSVExport::Clipboard) {
            setWindowTitle(i18n("Copy Data From Table to Clipboard"));
            infoLblFromText = i18n("Copying data from table:");
        } else {
            setWindowTitle(i18n("Export Data From Table to CSV File"));
            infoLblFromText = i18n("Exporting data from table:");
        }
    } else if (m_tableOrQuery->query()) {
        if (m_options.mode == KexiCSVExport::Clipboard) {
            setWindowTitle(i18n("Copy Data From Query to Clipboard"));
            infoLblFromText = i18n("Copying data from table:");
        } else {
            setWindowTitle(i18n("Export Data From Query to CSV File"));
            infoLblFromText = i18n("Exporting data from query:");
        }
    } else {
        msgh.showErrorMessage(KexiMainWindowIface::global()->project()->dbConnection(),
                              i18n("Could not open data for exporting."));
        m_cancelled = true;
        return;
    }
    // OK, source data found.

    // Setup pages

    // 1. File Save Page
    if (m_options.mode == KexiCSVExport::File) {
        m_fileSavePage = new KexiStartupFileWidget(
            KUrl("kfiledialog:///CSVImportExport"), //startDir
            KexiStartupFileWidget::Custom | KexiStartupFileWidget::SavingFileBasedDB,
            this);
        m_fileSavePage->setObjectName("m_fileSavePage");
        m_fileSavePage->setMinimumHeight(kapp->desktop()->availableGeometry().height() / 2);
        m_fileSavePage->setAdditionalFilters(csvMimeTypes().toSet());
        m_fileSavePage->setDefaultExtension("csv");
        m_fileSavePage->setLocationText(
            KexiUtils::stringToFileName(m_tableOrQuery->captionOrName()));
        connect(m_fileSavePage, SIGNAL(rejected()), this, SLOT(reject()));
        addPage(m_fileSavePage, i18n("Enter Name of File You Want to Save Data To"));
    }

    // 2. Export options
    m_exportOptionsPage = new QWidget(this);
    m_exportOptionsPage->setObjectName("m_exportOptionsPage");
    QGridLayout *exportOptionsLyr = new QGridLayout(m_exportOptionsPage);
    exportOptionsLyr->setObjectName("exportOptionsLyr");
    m_infoLblFrom = new KexiCSVInfoLabel(infoLblFromText, m_exportOptionsPage);
    KexiPart::Info *partInfo = Kexi::partManager().infoForClass(
            QString("org.kexi-project.%1").arg(m_tableOrQuery->table() ? "table" : "query"));
    if (partInfo)
        m_infoLblFrom->setIcon(partInfo->itemIcon());
    m_infoLblFrom->separator()->hide();
    exportOptionsLyr->addWidget(m_infoLblFrom, 0, 0, 0, 2);

    m_infoLblTo = new KexiCSVInfoLabel(
        (m_options.mode == KexiCSVExport::File) ? i18n("To CSV file:") : i18n("To clipboard:"),
        m_exportOptionsPage
    );
    if (m_options.mode == KexiCSVExport::Clipboard)
        m_infoLblTo->setIcon("edit-paste");
    exportOptionsLyr->addWidget(m_infoLblTo, 1, 0, 1, 3);

    m_showOptionsButton = new KPushButton(KGuiItem(i18n("Show Options >>"), "configure"),
                                          m_exportOptionsPage);
    connect(m_showOptionsButton, SIGNAL(clicked()), this, SLOT(slotShowOptionsButtonClicked()));
    exportOptionsLyr->addWidget(m_showOptionsButton, 2, 2, 0, 0);
    m_showOptionsButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    // -<options section>
    m_exportOptionsSection = new Q3GroupBox(1, Qt::Vertical, i18n("Options"), m_exportOptionsPage);
    m_exportOptionsSection->setObjectName("m_exportOptionsSection");
    m_exportOptionsSection->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    exportOptionsLyr->addWidget(m_exportOptionsSection, 3, 3, 0, 1);
    QWidget *exportOptionsSectionWidget
    = new QWidget(m_exportOptionsSection);
    exportOptionsSectionWidget->setObjectName("exportOptionsSectionWidget");
    QGridLayout *exportOptionsSectionLyr = new QGridLayout(exportOptionsSectionWidget);
    exportOptionsLyr->setObjectName("exportOptionsLyr");

    // -delimiter
    m_delimiterWidget = new KexiCSVDelimiterWidget(false, //!lineEditOnBottom
            exportOptionsSectionWidget);
    m_delimiterWidget->setDelimiter(defaultDelimiter());
    exportOptionsSectionLyr->addWidget(m_delimiterWidget, 0, 1);
    QLabel *delimiterLabel = new QLabel(i18n("Delimiter:"), exportOptionsSectionWidget);
    delimiterLabel->setBuddy(m_delimiterWidget);
    exportOptionsSectionLyr->addWidget(delimiterLabel, 0, 0);

    // -text quote
    QWidget *textQuoteWidget = new QWidget(exportOptionsSectionWidget);
    QHBoxLayout *textQuoteLyr = new QHBoxLayout(textQuoteWidget);
    exportOptionsSectionLyr->addWidget(textQuoteWidget, 1, 1);
    m_textQuote = new KexiCSVTextQuoteComboBox(textQuoteWidget);
    m_textQuote->setTextQuote(defaultTextQuote());
    textQuoteLyr->addWidget(m_textQuote);
    textQuoteLyr->addStretch(0);
    QLabel *textQuoteLabel = new QLabel(i18n("Text quote:"), exportOptionsSectionWidget);
    textQuoteLabel->setBuddy(m_textQuote);
    exportOptionsSectionLyr->addWidget(textQuoteLabel, 1, 0);

    // - character encoding
    m_characterEncodingCombo = new KexiCharacterEncodingComboBox(exportOptionsSectionWidget);
    m_characterEncodingCombo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    exportOptionsSectionLyr->addWidget(m_characterEncodingCombo, 2, 1);
    QLabel *characterEncodingLabel = new QLabel(i18n("Text encoding:"), exportOptionsSectionWidget);
    characterEncodingLabel->setBuddy(m_characterEncodingCombo);
    exportOptionsSectionLyr->addWidget(characterEncodingLabel, 2, 0);

    // - checkboxes
    m_addColumnNamesCheckBox = new QCheckBox(i18n("Add column names as the first row"),
            exportOptionsSectionWidget);
    m_addColumnNamesCheckBox->setChecked(true);
    exportOptionsSectionLyr->addWidget(m_addColumnNamesCheckBox, 3, 1);
//! @todo 1.1: for copying use "Always use above options for copying" string
    m_alwaysUseCheckBox = new QCheckBox(i18n("Always use above options for exporting"),
                                        m_exportOptionsPage);
    exportOptionsLyr->addWidget(m_alwaysUseCheckBox, 4, 4, 0, 1);
// exportOptionsSectionLyr->addWidget( m_alwaysUseCheckBox, 4, 1 );
    m_exportOptionsSection->hide();
    m_alwaysUseCheckBox->hide();
    // -</options section>

// exportOptionsLyr->setColumnStretch(3, 1);
    exportOptionsLyr->addItem(
        new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::MinimumExpanding), 5, 0, 1, 2);

// addPage(m_exportOptionsPage, i18n("Set Export Options"));
    addPage(m_exportOptionsPage,
            m_options.mode == KexiCSVExport::Clipboard ? i18n("Copying") : i18n("Exporting"));
    setFinishEnabled(m_exportOptionsPage, true);

    // load settings
    if (m_options.mode != KexiCSVExport::Clipboard
            && readBoolEntry("ShowOptionsInCSVExportDialog", false)) {
        show();
        slotShowOptionsButtonClicked();
    }
    if (readBoolEntry("StoreOptionsForCSVExportDialog", false)) {
        // load defaults:
        m_alwaysUseCheckBox->setChecked(true);
        QString s = readEntry("DefaultDelimiterForExportingCSVFiles", defaultDelimiter());
        if (!s.isEmpty())
            m_delimiterWidget->setDelimiter(s);
        s = readEntry("DefaultTextQuoteForExportingCSVFiles", defaultTextQuote());
        m_textQuote->setTextQuote(s); //will be invaliudated here, so not a problem
        s = readEntry("DefaultEncodingForExportingCSVFiles");
        if (!s.isEmpty())
            m_characterEncodingCombo->setSelectedEncoding(s);
        m_addColumnNamesCheckBox->setChecked(
            readBoolEntry("AddColumnNamesForExportingCSVFiles", true));
    }

    updateGeometry();

    // -keep widths equal on page #2:
    int width = qMax(m_infoLblFrom->leftLabel()->sizeHint().width(),
                     m_infoLblTo->leftLabel()->sizeHint().width());
    m_infoLblFrom->leftLabel()->setFixedWidth(width);
    m_infoLblTo->leftLabel()->setFixedWidth(width);
}