/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2003-02-10
 * Description : Camera type selection dialog
 *
 * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu>
 * Copyright (C) 2006-2009 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * This program 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 2, or (at your option)
 * any later version.
 *
 * This program 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.
 *
 * ============================================================ */

// TQt includes.

#include <tqcombobox.h>
#include <tqvgroupbox.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqradiobutton.h>
#include <tqlistview.h>
#include <tqvbuttongroup.h>
#include <tqlayout.h>
#include <tqwhatsthis.h>

// KDE includes.

#include <kiconloader.h>
#include <tdeglobalsettings.h>
#include <kactivelabel.h>
#include <kurlrequester.h>
#include <tdelocale.h>
#include <klineedit.h>
#include <kcursor.h>
#include <tdeapplication.h>

// Local includes.

#include "searchtextbar.h"
#include "gpcamera.h"
#include "cameraselection.h"
#include "cameraselection.moc"

namespace Digikam
{

class CameraSelectionPriv
{
public:

    CameraSelectionPriv()
    {
        listView         = 0;
        titleEdit        = 0;
        portButtonGroup  = 0;
        usbButton        = 0;
        serialButton     = 0;
        portPathLabel    = 0;
        portPathComboBox = 0;
        umsMountURL      = 0;
        searchBar        = 0;
    }

    TQVButtonGroup *portButtonGroup;

    TQRadioButton  *usbButton;
    TQRadioButton  *serialButton;

    TQLabel        *portPathLabel;

    TQComboBox     *portPathComboBox;

    TQString        UMSCameraNameActual;
    TQString        UMSCameraNameShown;
    TQString        PTPCameraNameShown;

    TQStringList    serialPortList;

    TQListView     *listView;

    KLineEdit     *titleEdit;

    KURLRequester *umsMountURL;

    SearchTextBar *searchBar;
};

CameraSelection::CameraSelection( TQWidget* parent )
               : KDialogBase(Plain, i18n("Camera Configuration"),
                             Help|Ok|Cancel, Ok, parent, 0, true, true)
{
    d = new CameraSelectionPriv;

    kapp->setOverrideCursor(KCursor::waitCursor());
    setHelp("cameraselection.anchor", "digikam");
    d->UMSCameraNameActual = TQString("Directory Browse");   // Don't be i18n!
    d->UMSCameraNameShown  = i18n("Mounted Camera");
    d->PTPCameraNameShown  = TQString("USB PTP Class Camera");

    TQGridLayout* mainBoxLayout = new TQGridLayout(plainPage(), 6, 1, 0, KDialog::spacingHint());
    mainBoxLayout->setColStretch(0, 10);
    mainBoxLayout->setRowStretch(6, 10);

    // --------------------------------------------------------------

    d->listView = new TQListView(plainPage());
    d->listView->addColumn(i18n("Camera List"));
    d->listView->setAllColumnsShowFocus(true);
    d->listView->setResizeMode(TQListView::LastColumn);
    d->listView->setMinimumWidth(350);
    TQWhatsThis::add(d->listView, i18n("<p>Select the camera name that you want to use. All "
                                      "default settings on the right panel "
                                      "will be set automatically.</p><p>This list has been generated "
                                      "using the gphoto2 library installed on your computer.</p>"));

    d->searchBar = new SearchTextBar(plainPage(), "CameraSelectionSearchBar");

    // --------------------------------------------------------------

    TQVGroupBox* titleBox = new TQVGroupBox( i18n("Camera Title"), plainPage() );
    d->titleEdit = new KLineEdit( titleBox );
    TQWhatsThis::add(d->titleEdit, i18n("<p>Set here the name used in digiKam interface to "
                                       "identify this camera.</p>"));

    // --------------------------------------------------------------

    d->portButtonGroup = new TQVButtonGroup( i18n("Camera Port Type"), plainPage() );
    d->portButtonGroup->setRadioButtonExclusive( true );

    d->usbButton = new TQRadioButton( d->portButtonGroup );
    d->usbButton->setText( i18n( "USB" ) );
    TQWhatsThis::add(d->usbButton, i18n("<p>Select this option if your camera is connected to your "
                    "computer using an USB cable.</p>"));

    d->serialButton = new TQRadioButton( d->portButtonGroup );
    d->serialButton->setText( i18n( "Serial" ) );
    TQWhatsThis::add(d->serialButton, i18n("<p>Select this option if your camera is connected to your "
                    "computer using a serial cable.</p>"));

    // --------------------------------------------------------------

    TQVGroupBox* portPathBox = new TQVGroupBox( i18n( "Camera Port Path" ), plainPage() );
    d->portPathLabel = new TQLabel( portPathBox);
    d->portPathLabel->setText( i18n( "Note: only for serial port camera" ) );

    d->portPathComboBox = new TQComboBox( false, portPathBox );
    d->portPathComboBox->setDuplicatesEnabled( false );
    TQWhatsThis::add(d->portPathComboBox, i18n("<p>Select the serial port to use on your computer. "
                    "This option is only required if you use a serial camera.</p>"));

    // --------------------------------------------------------------

    TQVGroupBox* umsMountBox = new TQVGroupBox(i18n("Camera Mount Path"), plainPage());

    TQLabel* umsMountLabel = new TQLabel( umsMountBox );
    umsMountLabel->setText(i18n("Note: only for USB/IEEE mass storage camera"));

    d->umsMountURL = new KURLRequester( TQString("/mnt/camera"), umsMountBox);
    d->umsMountURL->setMode(KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly);
    TQWhatsThis::add(d->umsMountURL, i18n("<p>Set here the mount path to use on your computer. This "
                                         "option is only required if you use a <b>USB Mass Storage</b> "
                                         "camera.</p>"));
    
    // --------------------------------------------------------------
    
    TQGroupBox* box2 = new TQGroupBox( 0, TQt::Vertical, plainPage() );
    box2->setFrameStyle( TQFrame::NoFrame );
    TQGridLayout* box2Layout = new TQGridLayout( box2->layout(), 1, 5 );

    TQLabel* logo = new TQLabel( box2 );

    TDEIconLoader* iconLoader = TDEApplication::kApplication()->iconLoader();
    logo->setPixmap(iconLoader->loadIcon("digikam", TDEIcon::NoGroup, 64, 
                    TDEIcon::DefaultState, 0, true));

    KActiveLabel* link = new KActiveLabel(box2);
    link->setText(i18n("<p>To set a <b>USB Mass Storage</b> camera<br>"
                       "(which looks like a removable drive when mounted on your desktop), please<br>"
                       "use <a href=\"umscamera\">%1</a> from camera list.</p>") 
                       .arg(d->UMSCameraNameShown));

    KActiveLabel* link2 = new KActiveLabel(box2);
    link2->setText(i18n("<p>To set a <b>Generic PTP USB Device</b><br>"
                        "(which uses the Picture Transfer Protocol), please<br>"
                        "use <a href=\"ptpcamera\">%1</a> from the camera list.</p>")
                        .arg(d->PTPCameraNameShown));

    KActiveLabel* explanation = new KActiveLabel(box2);
    explanation->setText(i18n("<p>A complete list of camera settings to use is<br>"
                              "available at <a href='http://www.teaser.fr/~hfiguiere/linux/digicam.html'>"
                              "this url</a>.</p>"));

    box2Layout->addMultiCellWidget(logo,        0, 0, 0, 0);
    box2Layout->addMultiCellWidget(link,        0, 1, 1, 1);
    box2Layout->addMultiCellWidget(link2,       2, 3, 1, 1);
    box2Layout->addMultiCellWidget(explanation, 4, 5, 1, 1);

    // --------------------------------------------------------------

    mainBoxLayout->addMultiCellWidget(d->listView,        0, 5, 0, 0);
    mainBoxLayout->addMultiCellWidget(d->searchBar,       6, 6, 0, 0);
    mainBoxLayout->addMultiCellWidget(titleBox,           0, 0, 1, 1);
    mainBoxLayout->addMultiCellWidget(d->portButtonGroup, 1, 1, 1, 1);
    mainBoxLayout->addMultiCellWidget(portPathBox,        2, 2, 1, 1);
    mainBoxLayout->addMultiCellWidget(umsMountBox,        3, 3, 1, 1);
    mainBoxLayout->addMultiCellWidget(box2,               4, 5, 1, 1);

    // Connections --------------------------------------------------

    disconnect(link, TQ_SIGNAL(linkClicked(const TQString &)),
               link, TQ_SLOT(openLink(const TQString &)));

    connect(link, TQ_SIGNAL(linkClicked(const TQString &)),
            this, TQ_SLOT(slotUMSCameraLinkUsed()));

    disconnect(link2, TQ_SIGNAL(linkClicked(const TQString &)),
               link2, TQ_SLOT(openLink(const TQString &)));

    connect(link2, TQ_SIGNAL(linkClicked(const TQString &)),
            this, TQ_SLOT(slotPTPCameraLinkUsed()));

    connect(d->listView, TQ_SIGNAL(selectionChanged(TQListViewItem *)),
            this, TQ_SLOT(slotSelectionChanged(TQListViewItem *)));

    connect(d->portButtonGroup, TQ_SIGNAL(clicked(int)),
            this, TQ_SLOT(slotPortChanged()));

    connect(this, TQ_SIGNAL(okClicked()),
            this, TQ_SLOT(slotOkClicked()));

    connect(d->searchBar, TQ_SIGNAL(signalTextChanged(const TQString&)),
            this, TQ_SLOT(slotSearchTextChanged(const TQString&)));

    // Initialize  --------------------------------------------------

    getCameraList();
    getSerialPortList();
    kapp->restoreOverrideCursor();
}

CameraSelection::~CameraSelection()
{
    delete d;
}

void CameraSelection::slotUMSCameraLinkUsed()
{
    TQListViewItem *item = d->listView->findItem(d->UMSCameraNameShown, 0);
    if (item)
    {
        d->listView->setCurrentItem(item);
        d->listView->ensureItemVisible(item);
    }
}

void CameraSelection::slotPTPCameraLinkUsed()
{
    TQListViewItem *item = d->listView->findItem(d->PTPCameraNameShown, 0);
    if (item)
    {
        d->listView->setCurrentItem(item);
        d->listView->ensureItemVisible(item);
    }
}

void CameraSelection::setCamera(const TQString& title, const TQString& model,
                                const TQString& port,  const TQString& path)
{
    TQString camModel(model);

    if (camModel == d->UMSCameraNameActual)
        camModel = d->UMSCameraNameShown;

    TQListViewItem* item = d->listView->findItem(camModel, 0);
    if (!item) return;

    d->listView->setSelected(item, true);
    d->listView->ensureItemVisible(item);

    d->titleEdit->setText(title);

    if (port.contains("usb"))
    {
        d->usbButton->setChecked(true);
        slotPortChanged();
    }
    else if (port.contains("serial")) 
    {
        d->serialButton->setChecked(true);

        for (int i=0; i<d->portPathComboBox->count(); i++) 
        {
            if (port == d->portPathComboBox->text(i)) 
            {
                d->portPathComboBox->setCurrentItem(i);
                break;
            }
        }
        slotPortChanged();
    }

    d->umsMountURL->setURL(path);
}

void CameraSelection::getCameraList()
{
    int count = 0;
    TQStringList clist;
    TQString cname;

    GPCamera::getSupportedCameras(count, clist);

    for (int i = 0 ; i < count ; i++) 
    {
        cname = clist[i];
        if (cname == d->UMSCameraNameActual)
            new TQListViewItem(d->listView, d->UMSCameraNameShown);
        else
            new TQListViewItem(d->listView, cname);
    }
}

void CameraSelection::getSerialPortList()
{
    TQStringList plist;

    GPCamera::getSupportedPorts(plist);

    d->serialPortList.clear();

    for (unsigned int i=0; i<plist.count(); i++)
    {
        if ((plist[i]).startsWith("serial:"))
            d->serialPortList.append(plist[i]);
    }
}

void CameraSelection::slotSelectionChanged(TQListViewItem *item)
{
    if (!item) return;

    TQString model(item->text(0));

    if (model == d->UMSCameraNameShown) 
    {
        model = d->UMSCameraNameActual;

        d->titleEdit->setText(model);

        d->serialButton->setEnabled(true);
        d->serialButton->setChecked(false);
        d->serialButton->setEnabled(false);
        d->usbButton->setEnabled(true);
        d->usbButton->setChecked(false);
        d->usbButton->setEnabled(false);
        d->portPathComboBox->setEnabled(true);
        d->portPathComboBox->insertItem(TQString("NONE"), 0);
        d->portPathComboBox->setEnabled(false);

        d->umsMountURL->setEnabled(true);
        d->umsMountURL->clear();
        d->umsMountURL->setURL(TQString("/mnt/camera"));
        return;
    }
    else 
    {
        d->umsMountURL->setEnabled(true);
        d->umsMountURL->clear();
        d->umsMountURL->setURL(TQString("/"));
        d->umsMountURL->setEnabled(false);
    }

    d->titleEdit->setText(model);

    TQStringList plist;
    GPCamera::getCameraSupportedPorts(model, plist);

    if (plist.contains("serial")) 
    {
        d->serialButton->setEnabled(true);
        d->serialButton->setChecked(true);
    }
    else 
    {
        d->serialButton->setEnabled(true);
        d->serialButton->setChecked(false);
        d->serialButton->setEnabled(false);
    }

    if (plist.contains("usb")) 
    {
        d->usbButton->setEnabled(true);
        d->usbButton->setChecked(true);
    }
    else 
    {
        d->usbButton->setEnabled(true);
        d->usbButton->setChecked(false);
        d->usbButton->setEnabled(false);
    }

    slotPortChanged();
}

void CameraSelection::slotPortChanged()
{
    if (d->usbButton->isChecked()) 
    {
        d->portPathComboBox->setEnabled(true);
        d->portPathComboBox->clear();
        d->portPathComboBox->insertItem( TQString("usb:"), 0 );
        d->portPathComboBox->setEnabled(false);
        return;
    }

    if (d->serialButton->isChecked()) 
    {
        d->portPathComboBox->setEnabled(true);
        d->portPathComboBox->clear();
        d->portPathComboBox->insertStringList(d->serialPortList);
    }
}

TQString CameraSelection::currentTitle()
{
    return d->titleEdit->text();
}

TQString CameraSelection::currentModel()
{
    TQListViewItem* item = d->listView->currentItem();
    if (!item)
        return TQString();

    TQString model(item->text(0));
    if (model == d->UMSCameraNameShown)
        model = d->UMSCameraNameActual;

    return model;
}

TQString CameraSelection::currentPortPath()
{
    return d->portPathComboBox->currentText();
}

TQString CameraSelection::currentCameraPath()
{
    return d->umsMountURL->url();
}

void CameraSelection::slotOkClicked()
{
    emit signalOkClicked(currentTitle(),    currentModel(),
                         currentPortPath(), currentCameraPath());
}

void CameraSelection::slotSearchTextChanged(const TQString& filter)
{
    bool query     = false;
    TQString search = filter.lower();

    TQListViewItemIterator it(d->listView);

    for ( ; it.current(); ++it ) 
    {
        TQListViewItem *item  = it.current();

        if (item->text(0).lower().contains(search))
        {
            query = true;
            item->setVisible(true);
        }
        else
        {
            item->setVisible(false);
        }
    }

    d->searchBar->slotSearchResult(query);
}

}  // namespace Digikam
