/***************************************************************************
                           videowidgetimpl.cpp
                           -------------------
    begin                : Sun Sep 6 2003
    copyright            : (C) 2003 by Dirk Ziegelmeier
    email                : dziegel@gmx.de
 ***************************************************************************/

/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include <kdebug.h>
#include <klocale.h>
#include <k3listview.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kfiledialog.h>
#include <kconfig.h>

#include <qcombobox.h>
#include <qpushbutton.h>
#include <qspinbox.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qimage.h>
#include <Q3CheckListItem>
#include <QImageReader>

#include "kdetv.h"
#include "cfgdata.h"
#include "kdetvview.h"
#include "sourcemanager.h"
#include "kdetvsrcplugin.h"
#include "videowidgetimpl.h"
#include "pluginconfigwidgetimpl.h"


class VideoPluginListItem : public Q3CheckListItem
{
public:
    VideoPluginListItem(K3ListView*, PluginDesc*);
    virtual ~VideoPluginListItem();

    PluginDesc* pd;
};

VideoPluginListItem::VideoPluginListItem(K3ListView *parent, PluginDesc *d)
    : Q3CheckListItem(parent, d->name, Q3CheckListItem::CheckBox)
{
    setText(1, d->author);
    setText(2, d->comment);
    pd = d;
    setOn(pd->enabled);
}

VideoPluginListItem::~VideoPluginListItem()
{
}



VideoWidgetImpl::VideoWidgetImpl(QWidget* parent, Kdetv* ktv, ConfigData* cfg)
    : QWidget(parent),
      SettingsDialogPage(i18n("Video"),
                         i18n("Configure Video Options"),
                         "tv"),
      _ktv(ktv),
      _cfg(cfg)
{
    setupUi(this);
    connect(_configure, SIGNAL(clicked()),
            this, SLOT(configurePlugin()));
    connect(_videoListView, SIGNAL(doubleClicked(Q3ListViewItem*)),
            this, SLOT(itemDoubleClicked(Q3ListViewItem*)));
    connect(_videoListView, SIGNAL(selectionChanged()),
            this, SLOT(selectionChanged()));
    connect(_browse, SIGNAL(clicked()),
            this, SLOT(browseClicked()));
}

VideoWidgetImpl::~VideoWidgetImpl()
{
}

void VideoWidgetImpl::setup()
{
    _videoListView->clear();
    for (QList<PluginDesc*>::iterator it = _ktv->pluginFactory()->videoPlugins().begin();
         it != _ktv->pluginFactory()->videoPlugins().end(); ++it) {
        _videoListView->insertItem(new VideoPluginListItem(_videoListView, (*it)));
    }
    selectionChanged();

    QList<QByteArray> supported_formats = QImageReader::supportedImageFormats();
    for(QList<QByteArray>::iterator it = supported_formats.begin(); it != supported_formats.end(); it++)
      _snapshotFormat->insertItem(0, *it);

    _snapshotFormat->setItemText(0, _cfg->snapshotFormat);
    _snapshotQuality->setValue(_cfg->snapshotQuality);
    _snapshotPath->setText(_cfg->snapshotPath);
    _snapshotSize->clear();
    for(int i=0; grab_resolutions[i].w != -1; i++) {
        _snapshotSize->insertItem(0, i18n(grab_resolutions[i].name));
    }
    _snapshotSize->setCurrentIndex(_cfg->snapshotRes);

    _fixAR->setChecked(_cfg->fixAR);
    _aspectCombo->setCurrentIndex(_cfg->ARmode);

    _configure->setEnabled(false);
}

void VideoWidgetImpl::defaults()
{
    const ConfigData& def = ConfigData::getDefaultConfig();

    _fixAR->setChecked(def.fixAR);
    _aspectCombo->setCurrentIndex(def.ARmode);
    _snapshotFormat->setItemText(0, def.snapshotFormat);
    _snapshotQuality->setValue(def.snapshotQuality);
    _snapshotPath->setText(def.snapshotPath);
    _snapshotSize->setCurrentIndex(def.snapshotRes);
}

void VideoWidgetImpl::selectionChanged()
{
    Q3ListViewItem* item = _videoListView->selectedItem();

    if ( !item ) {
        _configure->setEnabled(false);
        return;
    }

    PluginDesc* p = static_cast<VideoPluginListItem*>(item)->pd;
    _configure->setEnabled(p->configurable);
}

void VideoWidgetImpl::itemDoubleClicked(Q3ListViewItem*)
{
    configurePlugin();
}

void VideoWidgetImpl::browseClicked()
{
    KFileDialog dlg(KUrl(_snapshotPath->text()),
                    "*", this
                    /*FIXME: KDE4 migration: removing this parameters:
                    0L,
                    "DirSelectDialog",
                    true*/);
    
    dlg.setMode( KFile::Directory | KFile::ExistingOnly );

    if (dlg.exec() == KFileDialog::Accepted) {
        _snapshotPath->setText(dlg.selectedFile());
    }
}

void VideoWidgetImpl::configurePlugin()
{
    VideoPluginListItem* i = static_cast<VideoPluginListItem*>(_videoListView->selectedItem());
    if (!i) return;
    PluginDesc* pd         = i->pd;
    if (!pd->configurable) return;

    bool previousState   = pd->enabled;
    pd->enabled          = true;
    KdetvSourcePlugin* p = _ktv->pluginFactory()->getSourcePlugin(pd, _ktv->screen());
    pd->enabled          = previousState;
    p->probeDevices();

    PluginConfigWidgetImpl w(0L, "Video Plugin Config Dialog", true);
    w.setConfigWidget(pd->name, p->configWidget(&w, "Video Source Configuration Widget"));
    if (w.exec() == QDialog::Accepted) {
        p->saveConfig();
    }

    p->destroy();
}

void VideoWidgetImpl::apply()
{
    bool rescanNecessary = false;

    _cfg->fixAR           = _fixAR->isChecked();
    _cfg->ARmode          = _aspectCombo->currentIndex();
    _cfg->snapshotPath    = _snapshotPath->text();
    _cfg->snapshotQuality = _snapshotQuality->value();
    _cfg->snapshotFormat  = _snapshotFormat->currentText();
    _cfg->snapshotRes     = _snapshotSize->currentIndex();

    KConfigGroup video_cfg(_cfg->pluginConfigHandle(), "Video Plugins");
    for (Q3ListViewItemIterator it(_videoListView);
         it.current();
         it++) {
        VideoPluginListItem* item = static_cast<VideoPluginListItem*>(it.current());
        if (item->pd->enabled != item->isOn()) {
            rescanNecessary = true;
        }
        item->pd->enabled = item->isOn();
        video_cfg.writeEntry(item->pd->name + "-" + item->pd->author, item->pd->enabled);
    }

    if (rescanNecessary) {
        _ktv->stop();
        _ktv->sourceManager()->scanPlugins();
        _ktv->start();
    }
}

#include "videowidgetimpl.moc"
