/***************************************************************************
                           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 <klistview.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 "kdetv.h"
#include "cfgdata.h"
#include "kdetvview.h"
#include "sourcemanager.h"
#include "kdetvsrcplugin.h"
#include "videowidgetimpl.h"
#include "pluginconfigwidget.h"


class VideoPluginListItem : public QCheckListItem
{
public:
    VideoPluginListItem(KListView*, PluginDesc*);
    virtual ~VideoPluginListItem();

    PluginDesc* pd;
};

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

VideoPluginListItem::~VideoPluginListItem()
{
}



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

VideoWidgetImpl::~VideoWidgetImpl()
{
}

void VideoWidgetImpl::setup()
{
    _videoListView->clear();
    for (PluginDesc *p = _ktv->pluginFactory()->videoPlugins().first();
         p;
         p = _ktv->pluginFactory()->videoPlugins().next())
        {
            _videoListView->insertItem(new VideoPluginListItem(_videoListView, p));
        }
    selectionChanged();

    _snapshotFormat->insertStrList(QImageIO::inputFormats());
    _snapshotFormat->setCurrentText(_cfg->snapshotFormat);
    _snapshotQuality->setValue(_cfg->snapshotQuality);
    _snapshotPath->setText(_cfg->snapshotPath);
    for(int i=0; grab_resolutions[i].w != -1; i++) {
        _snapshotSize->insertItem(i18n(grab_resolutions[i].name));
    }
    _snapshotSize->setCurrentItem(_cfg->snapshotRes);

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

    _configure->setEnabled(false);
}

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

    _fixAR->setChecked(def.fixAR);
    _aspectCombo->setCurrentItem(def.ARmode);
    _snapshotFormat->setCurrentText(def.snapshotFormat);
    _snapshotQuality->setValue(def.snapshotQuality);
    _snapshotPath->setText(def.snapshotPath);
    _snapshotSize->setCurrentItem(def.snapshotRes);
}

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

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

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

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

void VideoWidgetImpl::browseClicked()
{
    KFileDialog dlg(_snapshotPath->text(),
                    "*",
                    0L,
                    "DirSelectDialog",
                    true);

    dlg.setMode( KFile::Directory | KFile::ExistingOnly );

    if (dlg.exec() == KDialog::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();

    PluginConfigWidget 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->currentItem();
    _cfg->snapshotPath    = _snapshotPath->text();
    _cfg->snapshotQuality = _snapshotQuality->value();
    _cfg->snapshotFormat  = _snapshotFormat->currentText();
    _cfg->snapshotRes     = _snapshotSize->currentItem();

    _cfg->pluginConfigHandle()->setGroup("Video Plugins");
    for (QListViewItemIterator 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();
        _cfg->pluginConfigHandle()->writeEntry(item->pd->name + "-" + item->pd->author, item->pd->enabled);
    }

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

#include "videowidgetimpl.moc"
