/*
    Rosegarden
    A MIDI and audio sequencer and musical notation editor.
 
    This program is Copyright 2000-2008
        Guillaume Laurent   <glaurent@telegraph-road.org>,
        Chris Cannam        <cannam@all-day-breakfast.com>,
        Richard Bown        <richard.bown@ferventsoftware.com>
 
    The moral rights of Guillaume Laurent, Chris Cannam, and Richard
    Bown to claim authorship of this work have been asserted.
 
    Other copyrights also apply to some parts of this work.  Please
    see the AUTHORS file and individual file headers for details.
 
    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 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/


#include "ControlEditorDialog.h"
#include <tqlayout.h>
#include <tdeapplication.h>

#include <tdelocale.h>
#include "misc/Debug.h"
#include "misc/Strings.h"
#include "base/Colour.h"
#include "base/Composition.h"
#include "base/ControlParameter.h"
#include "base/Device.h"
#include "base/Event.h"
#include "base/MidiDevice.h"
#include "base/MidiTypes.h"
#include "base/Studio.h"
#include "commands/studio/AddControlParameterCommand.h"
#include "commands/studio/ModifyControlParameterCommand.h"
#include "commands/studio/RemoveControlParameterCommand.h"
#include "ControlParameterEditDialog.h"
#include "ControlParameterItem.h"
#include "document/MultiViewCommandHistory.h"
#include "document/RosegardenGUIDoc.h"
#include "document/ConfigGroups.h"
#include <tdeaction.h>
#include <kcommand.h>
#include <tdelistview.h>
#include <tdemainwindow.h>
#include <tdestdaccel.h>
#include <kstdaction.h>
#include <tqcolor.h>
#include <tqdialog.h>
#include <tqframe.h>
#include <tqlabel.h>
#include <tqlistview.h>
#include <tqpixmap.h>
#include <tqptrlist.h>
#include <tqpushbutton.h>
#include <tqsizepolicy.h>
#include <tqstring.h>
#include <tqtooltip.h>
#include <tqvbox.h>
#include <tqwidget.h>


namespace Rosegarden
{

const TQString notShowing(i18n("<not showing>"));

ControlEditorDialog::ControlEditorDialog(TQWidget *parent,
        RosegardenGUIDoc *doc,
        DeviceId device):
        TDEMainWindow(parent, "controleditordialog"),
        m_studio(&doc->getStudio()),
        m_doc(doc),
        m_device(device),
        m_modified(false)
{
    RG_DEBUG << "ControlEditorDialog::ControlEditorDialog: device is " << m_device << endl;

    TQVBox* mainFrame = new TQVBox(this);
    setCentralWidget(mainFrame);

    setCaption(i18n("Manage Control Events"));

    TQString deviceName(i18n("<no device>"));
    MidiDevice *md =
        dynamic_cast<MidiDevice *>(m_studio->getDevice(m_device));
    if (md)
        deviceName = strtoqstr(md->getName());

    // spacing hack!
    new TQLabel("", mainFrame);
    new TQLabel(i18n("  Control Events for %1 (device %2)").arg(deviceName).
               arg(device), mainFrame);
    new TQLabel("", mainFrame);

    m_listView = new TDEListView(mainFrame);
    m_listView->addColumn(i18n("Control Event name  "));
    m_listView->addColumn(i18n("Control Event type  "));
    m_listView->addColumn(i18n("Control Event value  "));
    m_listView->addColumn(i18n("Description  "));
    m_listView->addColumn(i18n("Min  "));
    m_listView->addColumn(i18n("Max  "));
    m_listView->addColumn(i18n("Default  "));
    m_listView->addColumn(i18n("Color  "));
    m_listView->addColumn(i18n("Position on instrument panel"));

    m_listView->setColumnAlignment(0, TQt::AlignLeft);

    // Align remaining columns centrally
    for (int i = 1; i < 9; ++i)
        m_listView->setColumnAlignment(i, TQt::AlignHCenter);

    m_listView->restoreLayout(kapp->config(), ControlEditorConfigGroup);

    TQFrame* btnBox = new TQFrame(mainFrame);

    btnBox->setSizePolicy(
        TQSizePolicy(TQSizePolicy::Minimum, TQSizePolicy::Fixed));

    TQHBoxLayout* layout = new TQHBoxLayout(btnBox, 4, 10);

    m_addButton = new TQPushButton(i18n("Add"), btnBox);
    m_deleteButton = new TQPushButton(i18n("Delete"), btnBox);

    m_closeButton = new TQPushButton(i18n("Close"), btnBox);

    TQToolTip::add
        (m_addButton,
                i18n("Add a Control Parameter to the Studio"));

    TQToolTip::add
        (m_deleteButton,
                i18n("Delete a Control Parameter from the Studio"));

    TQToolTip::add
        (m_closeButton,
                i18n("Close the Control Parameter editor"));

    layout->addStretch(10);
    layout->addWidget(m_addButton);
    layout->addWidget(m_deleteButton);
    layout->addSpacing(30);

    layout->addWidget(m_closeButton);
    layout->addSpacing(5);

    connect(m_addButton, TQ_SIGNAL(released()),
            TQ_SLOT(slotAdd()));

    connect(m_deleteButton, TQ_SIGNAL(released()),
            TQ_SLOT(slotDelete()));

    setupActions();

    m_doc->getCommandHistory()->attachView(actionCollection());
    connect(m_doc->getCommandHistory(), TQ_SIGNAL(commandExecuted()),
            this, TQ_SLOT(slotUpdate()));

    connect(m_listView, TQ_SIGNAL(doubleClicked(TQListViewItem *)),
            TQ_SLOT(slotEdit(TQListViewItem *)));

    // Highlight all columns - enable extended selection mode
    //
    m_listView->setAllColumnsShowFocus(true);
    m_listView->setSelectionMode(TQListView::Extended);

    initDialog();

    setAutoSaveSettings(ControlEditorConfigGroup, true);
}

ControlEditorDialog::~ControlEditorDialog()
{
    RG_DEBUG << "\n*** ControlEditorDialog::~ControlEditorDialog\n" << endl;

    m_listView->saveLayout(kapp->config(), ControlEditorConfigGroup);

    if (m_doc)
        m_doc->getCommandHistory()->detachView(actionCollection());
}

void
ControlEditorDialog::initDialog()
{
    RG_DEBUG << "ControlEditorDialog::initDialog" << endl;
    slotUpdate();
}

void
ControlEditorDialog::slotUpdate()
{
    RG_DEBUG << "ControlEditorDialog::slotUpdate" << endl;

    //TQPtrList<TQListViewItem> selection = m_listView->selectedItems();

    MidiDevice *md =
        dynamic_cast<MidiDevice *>(m_studio->getDevice(m_device));
    if (!md)
        return ;

    ControlList::const_iterator it = md->beginControllers();
    TQListViewItem *item;
    int i = 0;

    m_listView->clear();

    for (; it != md->endControllers(); ++it) {
        Composition &comp = m_doc->getComposition();

        TQString colour =
            strtoqstr(comp.getGeneralColourMap().getNameByIndex(it->getColourIndex()));

        if (colour == "")
            colour = i18n("<default>");

        TQString position = TQString("%1").arg(it->getIPBPosition());
        if (position.toInt() == -1)
            position = notShowing;

        TQString value;
        value.sprintf("%d (0x%x)", it->getControllerValue(),
                      it->getControllerValue());

        if (it->getType() == PitchBend::EventType) {
            item = new ControlParameterItem(i++,
                                            m_listView,
                                            strtoqstr(it->getName()),
                                            strtoqstr(it->getType()),
                                            TQString("-"),
                                            strtoqstr(it->getDescription()),
                                            TQString("%1").arg(it->getMin()),
                                            TQString("%1").arg(it->getMax()),
                                            TQString("%1").arg(it->getDefault()),
                                            colour,
                                            position);
        } else {
            item = new ControlParameterItem(i++,
                                            m_listView,
                                            strtoqstr(it->getName()),
                                            strtoqstr(it->getType()),
                                            value,
                                            strtoqstr(it->getDescription()),
                                            TQString("%1").arg(it->getMin()),
                                            TQString("%1").arg(it->getMax()),
                                            TQString("%1").arg(it->getDefault()),
                                            colour,
                                            position);
        }


        // create and set a colour pixmap
        //
        TQPixmap colourPixmap(16, 16);
        Colour c = comp.getGeneralColourMap().getColourByIndex(it->getColourIndex());
        colourPixmap.fill(TQColor(c.getRed(), c.getGreen(), c.getBlue()));
        item->setPixmap(7, colourPixmap);

        m_listView->insertItem(item);
    }

    if (m_listView->childCount() == 0) {
        TQListViewItem *item = new TQListViewItem(m_listView, i18n("<none>"));
        m_listView->insertItem(item);

        m_listView->setSelectionMode(TQListView::NoSelection);
    } else {
        m_listView->setSelectionMode(TQListView::Extended);
    }


}

/*
void
ControlEditorDialog::slotEditCopy()
{
    RG_DEBUG << "ControlEditorDialog::slotEditCopy" << endl;
}

void
ControlEditorDialog::slotEditPaste()
{
    RG_DEBUG << "ControlEditorDialog::slotEditPaste" << endl;
}
*/

void
ControlEditorDialog::slotAdd()
{
    RG_DEBUG << "ControlEditorDialog::slotAdd to device " << m_device << endl;

    AddControlParameterCommand *command =
        new AddControlParameterCommand(m_studio, m_device,
                                       ControlParameter());

    addCommandToHistory(command);
}

void
ControlEditorDialog::slotDelete()
{
    RG_DEBUG << "ControlEditorDialog::slotDelete" << endl;

    if (!m_listView->currentItem())
        return ;

    ControlParameterItem *item =
        dynamic_cast<ControlParameterItem*>(m_listView->currentItem());

    if (item) {
        RemoveControlParameterCommand *command =
            new RemoveControlParameterCommand(m_studio, m_device, item->getId());

        addCommandToHistory(command);
    }
}

void
ControlEditorDialog::slotClose()
{
    RG_DEBUG << "ControlEditorDialog::slotClose" << endl;

    if (m_doc)
        m_doc->getCommandHistory()->detachView(actionCollection());
    m_doc = 0;

    close();
}

void
ControlEditorDialog::setupActions()
{
    TDEAction* close = KStdAction::close(this,
                                       TQ_SLOT(slotClose()),
                                       actionCollection());

    m_closeButton->setText(close->text());
    connect(m_closeButton, TQ_SIGNAL(released()), this, TQ_SLOT(slotClose()));

    // some adjustments
    new TDEToolBarPopupAction(i18n("Und&o"),
                            "edit-undo",
                            TDEStdAccel::key(TDEStdAccel::Undo),
                            actionCollection(),
                            KStdAction::stdName(KStdAction::Undo));

    new TDEToolBarPopupAction(i18n("Re&do"),
                            "edit-redo",
                            TDEStdAccel::key(TDEStdAccel::Redo),
                            actionCollection(),
                            KStdAction::stdName(KStdAction::Redo));

    createGUI("controleditor.rc");
}

void
ControlEditorDialog::addCommandToHistory(KCommand *command)
{
    getCommandHistory()->addCommand(command);
    setModified(false);
}

MultiViewCommandHistory*
ControlEditorDialog::getCommandHistory()
{
    return m_doc->getCommandHistory();
}

void
ControlEditorDialog::setModified(bool modified)
{
    RG_DEBUG << "ControlEditorDialog::setModified(" << modified << ")" << endl;

    if (modified) {}
    else {}

    m_modified = modified;
}

void
ControlEditorDialog::checkModified()
{
    RG_DEBUG << "ControlEditorDialog::checkModified(" << m_modified << ")"
    << endl;

}

void
ControlEditorDialog::slotEdit()
{}

void
ControlEditorDialog::slotEdit(TQListViewItem *i)
{
    RG_DEBUG << "ControlEditorDialog::slotEdit" << endl;

    ControlParameterItem *item =
        dynamic_cast<ControlParameterItem*>(i);

    MidiDevice *md =
        dynamic_cast<MidiDevice *>(m_studio->getDevice(m_device));

    if (item && md) {
        ControlParameterEditDialog dialog
        (this,
         md->getControlParameter(item->getId()), m_doc);

        if (dialog.exec() == TQDialog::Accepted) {
            ModifyControlParameterCommand *command =
                new ModifyControlParameterCommand(m_studio,
                                                  m_device,
                                                  dialog.getControl(),
                                                  item->getId());

            addCommandToHistory(command);
        }
    }
}

void
ControlEditorDialog::closeEvent(TQCloseEvent *e)
{
    emit closing();
    TDEMainWindow::closeEvent(e);
}

void
ControlEditorDialog::setDocument(RosegardenGUIDoc *doc)
{
    // reset our pointers
    m_doc = doc;
    m_studio = &doc->getStudio();
    m_modified = false;

    slotUpdate();
}

}
#include "ControlEditorDialog.moc"
