/*
 *
 * Copyright (C) 2002 Rich Moore <rich@kde.org>
 * Copyright (C) 2002 George Staikos <staikos@kde.org>
 *
 * 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 <qcheckbox.h>
#include <qcombobox.h>
#include <qmessagebox.h>
#include <qprogressbar.h>
#include <qpushbutton.h>
#include <qhbox.h>
#include <qtabdialog.h>
#include <qtextbrowser.h>
#include <qslider.h>
#include <qspinbox.h>

#include <kapplication.h>
#include <kdebug.h>
#include <kdialogbase.h>
#include <klocale.h>
#include <kmessagebox.h>

#include "channelscanner.h"
#include "channeleditor.h"
#include "controlwidgetimpl.h"
#include "kdetv.h"
#include "sourcemanager.h"
#include "pluginfactory.h"
#include "settingsdialog.h"
#include "settingsdialogpage.h"
#include "cfgdata.h"
#include "channelimportdlgimpl.h"
#include "channelwidgetimpl.h"
#include "filtermanager.h"
#include "kdetvvideo/kdetvimagefilter.h"

#include "viewmanager.h"
#include "viewmanager.moc"

ViewManager::ViewManager( Kdetv *kdetv, const char *name )
    : QObject( kdetv, name ? name : "view_manager" ),
      srcm( kdetv->sourceManager() ),
      ktv( kdetv ),
      cfg( kdetv->config() ),
      oldConfig(ConfigData::getDefaultConfig())
{
    connect( ktv->sourceManager(), SIGNAL( deviceChanged( const QString& ) ),
             this, SLOT( update() ) );
}

ViewManager::~ViewManager()
{

}

void ViewManager::update()
{
    cfg = ktv->config();
}

void ViewManager::launchImportDefault( QWidget *parent )
{
    ChannelImportDlgImpl* d = new ChannelImportDlgImpl(ktv, parent, "ImportDlg",
                                                       true, Qt::WDestructiveClose);
    d->show();
}

void ViewManager::launchWizard( QWidget* parent )
{
    if (!srcm->hasDevice()) return;

    ChannelScanner* chscan = new ChannelScanner(ktv, parent, "Channel Wizard",
                                                true, Qt::WDestructiveClose);
    chscan->show();
}

void ViewManager::launchControls( QWidget *parent )
{
    if (!srcm->hasDevice()) return;
    kdDebug() << "ViewManager::launchControls()" << endl;

    KDialogBase* dlg = new KDialogBase(parent, "SettingsPage", true, i18n("TV Card Controls"),
                                       KDialogBase::Ok | KDialogBase::Cancel | KDialogBase::Default,
                                       KDialogBase::Ok, true);

    QHBox* hbox = dlg->makeHBoxMainWidget();
    ControlWidget* w = new ControlWidgetImpl(srcm->controls(), ktv->channel(), srcm->device(),
                                             hbox, "ControlWidget");

    connect(dlg, SIGNAL( defaultClicked() ),
            w, SLOT( defaults() ));
    connect(dlg, SIGNAL( okClicked() ),
            w, SLOT( apply() ));
    connect(dlg, SIGNAL( cancelClicked() ),
            w, SLOT( cancel() ));
    connect(dlg, SIGNAL( finished() ),
            dlg, SLOT( deleteLater() ));

    dlg->show();
}

void ViewManager::launchChannelEditor( QWidget *parent )
{
    if (!srcm->hasDevice()) return;
    kdDebug() << "ViewManager::launchChannelEditor()" << endl;

    ChannelWidgetImpl* w = new ChannelWidgetImpl(0L, ktv, cfg);
    launchDialog(parent, w, "Channel Editor");
}

void ViewManager::launchDialog(QWidget* parent, QWidget* p, const QString& caption)
{
    KDialogBase* dlg = new KDialogBase(parent, "SettingsPage", true, i18n(caption.local8Bit()),
                                       KDialogBase::Ok | KDialogBase::Cancel | KDialogBase::Default,
                                       KDialogBase::Ok, true);

    QHBox *hbox = dlg->makeHBoxMainWidget();
    p->reparent(hbox, QPoint(0, 0));

    SettingsDialogPage* sdlg = dynamic_cast<SettingsDialogPage*>(p);
    sdlg->setup();

    connect(dlg, SIGNAL( defaultClicked() ),
            p, SLOT( defaults() ));
    connect(dlg, SIGNAL( okClicked() ),
            p, SLOT( apply() ));
    connect(dlg, SIGNAL( cancelClicked() ),
            p, SLOT( cancel() ));
    connect(dlg, SIGNAL( finished() ),
            dlg, SLOT( deleteLater() ));

    dlg->show();
}

void ViewManager::launchSettings( QWidget *parent )
{
    createSettings(parent)->show();
}

KDialogBase* ViewManager::createSettings( QWidget *parent )
{
    oldConfig = *cfg;

    QPtrList<SettingsDialogPage> p;
    for (QPtrListIterator<SettingsDialogPageFactory>fit(_pageFactories);
         fit.current() != 0;
         ++fit) {
        QPtrList<SettingsDialogPage>* temp = (*fit)->getPages();

        for (QPtrListIterator<SettingsDialogPage>pit(*temp);
             pit.current() != 0;
             ++pit) {
            p.append(*pit);
        }

        delete temp;
    }

    SettingsDialog* settingsDialog = new SettingsDialog(parent, 0, true, ktv,
                                                        &p, Qt::WDestructiveClose);
    connect(settingsDialog, SIGNAL( optionsModified() ),
            this, SLOT( setOptions() ));

    return settingsDialog;
}

void ViewManager::registerPageFactory(SettingsDialogPageFactory* f)
{
    _pageFactories.append(f);
}

void ViewManager::unregisterPageFactory(SettingsDialogPageFactory* f)
{
    _pageFactories.remove(f);
}

void ViewManager::setOptions()
{
    if (oldConfig.showSelectedOnly != cfg->showSelectedOnly)
        emit showSelectedChanged(cfg->showSelectedOnly);
    if (oldConfig.fixAR != cfg->fixAR)
        emit setFixedAspectRatio(cfg->fixAR, cfg->ARmode);
    if (oldConfig.ARmode != cfg->ARmode)
        emit setFixedAspectRatio(cfg->fixAR, cfg->ARmode);

    // Save the new options
    cfg->save();
} // setOptions

ChannelEditor *ViewManager::createChannelEditor( QWidget *parent )
{
    ChannelEditor *ce = new ChannelEditor( parent, ktv->sourceManager(),
                                           "chedit", cfg->showSelectedOnly );

    QString cap;
    if ( parent )
        cap = i18n("Channels");
    else
        cap = kapp->makeStdCaption(i18n("Channels"));

    ce->setCaption( cap );

    connect(ktv, SIGNAL(channelChanged(Channel*)),
            ce, SLOT(ensureSelected(Channel*)));

    return ce;
}

ConfigData *ViewManager::getConfig()
{
    return cfg;
}

void ViewManager::filterChainStatus(QWidget* parent)
{
    KDialogBase* dlg = new KDialogBase(i18n("Filter Chain Status"),
                                       KDialogBase::Ok,
                                       KDialogBase::Ok,
                                       KDialogBase::Ok,
                                       parent,
                                       "FilterChainStatus");

    QHBox* box = dlg->makeHBoxMainWidget();

    QTextBrowser* browser = new QTextBrowser(box, "TextBrowser");
    browser->setText(ktv->filterManager()->filterChain()->filterChainStatus());
    dlg->show();
}
