//
// C++ Implementation: 
//
// Description: 
//
//
// Author: Predrag Viceic <viceic@net2000.ch>, (C) 2005
//
// Copyright: See COPYING file that comes with this distribution
//
//


#include "midiconfigdialog.h"

MidiConfigDialog::MidiConfigDialog(MidiInput* mi,QWidget* parent, const char* name, bool modal, WFlags fl)
: MidiConfigDialogBase(parent,name, modal,fl)
{
    midiInput=mi;
    timer=new QTimer(this);
    connect(timer, SIGNAL(timeout()), SLOT(updateDeviceList()) );
    readablePortsListBox->setSelectionMode(QListBox::Single);
    selectedDeviceString="";
    selectedChannel=0;
}

MidiConfigDialog::~MidiConfigDialog()
{
}

/*$SPECIALIZATION$*/
void MidiConfigDialog::reject()
{
  timer->stop();
  QDialog::reject();
}

void MidiConfigDialog::accept()
{
  timer->stop();
  midiInput->openDevice(selectedDeviceString);
  midiInput->setMidiChannel(selectedChannel); //supposes that the stream is already opened !!!
  QDialog::accept();
}





/*!
    \fn MidiConfigDialog::setDefaults()
 */
void MidiConfigDialog::setDefaults()
{
    selectedDeviceString=midiInput->getDefaultDeviceString();
    selectedChannel=0;
    selectSelected();
}


/*!
    \fn MidiConfigDialog::updateDeviceList()
 */
void MidiConfigDialog::updateDeviceList()
{
    readablePortsListBox->clear();
    readablePortsListBox->insertStringList(midiInput->getDevices(),0);
    selectSelected();
}


/*!
    \fn MidiConfigDialog::exec () 
 */
int MidiConfigDialog::exec () 
{
    updateDeviceList();
    selectSelected();
    timer->start(1000);
    return QDialog::exec();
}


/*!
    \fn MidiConfigDialog::selectSelected()
 */
void MidiConfigDialog::selectSelected()
{
    if(selectedDeviceString==""){
        cout<<"selected MIDI device empty, reading devices...\n";
        selectedDeviceString=midiInput->getSelectedDeviceString();
    }
    for (uint i=0;i<readablePortsListBox->count();i++){
        if(readablePortsListBox->text(i)==selectedDeviceString){
            readablePortsListBox->setSelected(i,TRUE);
        }
    }
    QString midiChannelString=selectedChannel==0?"All":QString::number(selectedChannel);
    for (uint i=0;i<readablePortsListBox->count();i++){
        if(channelListBox->text(i)==midiChannelString){
            channelListBox->setSelected(i,TRUE);
        }
    }
}


/*!
    \fn MidiConfigDialog::selectionChanged(QListBoxItem * item)
 */
void MidiConfigDialog::selectionChanged(QListBoxItem * item)
{
    if(selectedDeviceString!=item->text()){
        selectedDeviceString=item->text();
        cout<<"Selected another MIDI device: "<<selectedDeviceString<<"\n";
    }
}

void MidiConfigDialog::midiPortChanged(QListBoxItem * item){
    if (item->text()=="All") selectedChannel=0;
    else selectedChannel=item->text().toInt();
}
