/*
 * soundpage.cpp - Sound settings for KTalkd
 *
 * Copyright (C) 1998 David Faure, faure@kde.org
 *
 * Requires the TQt widget libraries, available at no cost at
 * http://www.troll.no/
 *
 *  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.
 *
 *  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.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "soundpage.h"
#include <config.h>

#include <stdlib.h> //for setenv

#include <tqgroupbox.h>
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqlistbox.h>
#include <tqcheckbox.h>

#include <klineedit.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <tdelocale.h>
#include <kaudioplayer.h>
#include <tdemessagebox.h>
#include <kurlrequester.h>
#include <kurldrag.h>
#include <kdialog.h>

/* Lots of stuff taken from syssound.cpp */

KSoundPageConfig::KSoundPageConfig( TQWidget *parent, const char* name,
	KSimpleConfig *_config, KSimpleConfig *_announceconfig)
    : TDECModule (parent, name)
{
	if (!_config) {
		delete_config = true;
		config = new KSimpleConfig("ktalkdrc");
		announceconfig = new KSimpleConfig("");
	}
	else {
		delete_config = false;
		config = _config;
		announceconfig = _announceconfig;
	}

    TQBoxLayout* toplay = new TQVBoxLayout(this, KDialog::marginHint(),
        KDialog::spacingHint() );

    TQGroupBox* extprg_box = new TQGroupBox(this);
    extprg_box->setColumnLayout( 0, TQt::Horizontal );
    toplay->addWidget(extprg_box);

    TQGridLayout* l = new TQGridLayout(extprg_box->layout());

    extprg_edit = new KURLRequester(extprg_box);
    l->addWidget(extprg_edit, 2, 4);

    extprg_label = new TQLabel(extprg_edit,i18n("&Announcement program:"), extprg_box);
    l->addWidget(extprg_label, 2, 2);

    client_edit = new KURLRequester(extprg_box);
    l->addWidget(client_edit, 4, 4);

    client_label = new TQLabel(client_edit,i18n("&Talk client:"), extprg_box);
    l->addWidget(client_label, 4, 2);

    toplay->addSpacing(10);

    sound_cb = new TQCheckBox(i18n("&Play sound"), this);
    toplay->addWidget(sound_cb);

    TQGroupBox* sound_box = new TQGroupBox(this);
    toplay->addWidget(sound_box);

    TQBoxLayout* lay = new TQVBoxLayout(sound_box, 10, 10);

	int edit_h = client_edit->height(); // The height of a TQLineEdit

    sound_list = new TQListBox(sound_box);
    sound_list->setMinimumHeight( 3 * edit_h );
    sound_list->setAcceptDrops(true);
    sound_list->installEventFilter(this);

    sound_label = new TQLabel(sound_list,i18n("&Sound file:"), sound_box);
    lay->addWidget(sound_label);

    TQBoxLayout* l2 = new TQHBoxLayout(lay, 10);
    l2->addWidget(sound_list);

    btn_test = new TQPushButton(i18n("&Test"), sound_box);
    l2->addWidget(btn_test);

    sound_tip = new TQLabel(
        i18n("Additional WAV files can be dropped onto the sound list."),
        sound_box);

    lay->addWidget(sound_tip);

    TQStringList strlist( TDEGlobal::dirs()->findAllResources( "sound" ) );
    sound_list->insertStringList( strlist );

    load();

    connect(sound_cb, TQT_SIGNAL(clicked()), this, TQT_SLOT(soundOnOff()));
    connect(btn_test, TQT_SIGNAL(clicked()), this, TQT_SLOT(playCurrentSound()));

	// emit changed(true) on changes
	connect(extprg_edit->lineEdit(), TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(slotChanged()));
	connect(client_edit->lineEdit(), TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(slotChanged()));
}

KSoundPageConfig::~KSoundPageConfig( ) {
	if (delete_config) {
		delete config;
		delete announceconfig;
	}
    delete extprg_label;
    delete extprg_edit;
    delete client_label;
    delete client_edit;
    delete sound_cb;
    delete sound_label;
    delete sound_list;
    delete sound_tip;
    delete btn_test;

}

void KSoundPageConfig::slotChanged() {
	emit changed(true);
}

bool KSoundPageConfig::eventFilter(TQObject* /*o*/, TQEvent* e)
{
    if (e->type() == TQEvent::DragEnter) {
        sound_listDragEnterEvent((TQDragEnterEvent *) e);
        return true;
    }

    if (e->type() == TQEvent::Drop) {
        sound_listDropEvent((TQDropEvent *) e);
        return true;
    }

    return false;
}


void KSoundPageConfig::sound_listDragEnterEvent(TQDragEnterEvent* e)
{
    e->accept(KURLDrag::canDecode(e));
}

void KSoundPageConfig::sound_listDropEvent(TQDropEvent* e){

  KURL::List list;
  // This should never happen, but anyway...
  if(!KURLDrag::decode(e, list))
      return;

  // For now, we do only accept FILES ending with .wav...
  for( KURL::List::ConstIterator it = list.begin();
       it != list.end(); ++it)
  {
    const KURL &url = *it;

    if (!url.isLocalFile()) {      // for now, only file URLs are supported

      KMessageBox::sorry(this,
        i18n("This type of URL is currently unsupported "\
              "by the TDE system sound module."),
		i18n("Unsupported URL"));

    }
    else
    { // Now check for the ending ".wav"

      if (url.path().right(4).upper() != ".WAV") {
        TQString msg = i18n("%1\ndoes not appear "\
                            "to be a WAV file.").arg(url.path());

        KMessageBox::sorry(this, msg, i18n("Improper File Extension"));

      }
      else
      {  // Hurra! Finally we've got a WAV file to add to the list

        if (!addToSound_List(url.path())) {
          // did not add file because it is already in the list
          TQString msg = i18n("The file %1 is already in the list").arg(url.path());

          KMessageBox::information(this, msg, i18n("File Already in List"));

        }
      }
    }
  }
}

int KSoundPageConfig::findInSound_List(TQString sound) {
// Searches for <sound> in sound_list. Returns position or -1 if not found

  bool found = false;

  int i = 0;
  int len = sound_list->count();

  while ((!found) && (i < len)) {

    found = sound == sound_list->text(i);
    i++;
  }
  return (found ? i-1 : -1);
}

bool KSoundPageConfig::addToSound_List(TQString sound){
// Add "sound" to the sound list, but only if it is not already there

 bool found = (findInSound_List(sound) != -1);
 if (!found) {   // Fine, the sound is not already in the sound list!

   TQString *tmp = new TQString(sound); // take a copy...
   sound_list->insertItem(*tmp);
   sound_list->setTopItem(sound_list->count()-1);

   slotChanged();
 }

 return !found;
}

void KSoundPageConfig::playCurrentSound()
{
  TQString hlp, sname;
  int soundno;

  soundno = sound_list->currentItem();
  if (soundno != -1) {
    sname = sound_list->text(soundno);
    if (sname[0] != '/')
      KAudioPlayer::play(locate("sound", sname));
    else
      KAudioPlayer::play(sname);
  }
}

void KSoundPageConfig::soundOnOff()
{
    bool b = sound_cb->isChecked();
    sound_label->setEnabled(b);
    sound_list->setEnabled(b);
    btn_test->setEnabled(b);
    sound_tip->setEnabled(b);

	slotChanged();
}

void KSoundPageConfig::defaults() {

    extprg_edit->lineEdit()->setText(TDEStandardDirs::findExe("ktalkdlg"));
    client_edit->lineEdit()->setText(TDEStandardDirs::findExe("konsole")+" -e talk");
       // will be ktalk when ktalk is in CVS.
    sound_cb->setChecked(true);

    // Activate things according to configuration
    soundOnOff();
}

void KSoundPageConfig::load() {

    config->setGroup("ktalkd");
    announceconfig->setGroup("ktalkannounce");

    setenv("TDEBINDIR",TQFile::encodeName(TDEStandardDirs::kde_default("exe")),false/*don't overwrite*/);
           // for the first reading of  the config file

    extprg_edit->lineEdit()->setText(config->readPathEntry("ExtPrg",
	TDEStandardDirs::findExe("ktalkdlg")));
    client_edit->lineEdit()->setText(announceconfig->readPathEntry("talkprg",
	TDEStandardDirs::findExe("konsole")+" -e talk")); // will be ktalk when ktalk is in CVS

    bool b = announceconfig->readBoolEntry("Sound",true/*default value*/);
    sound_cb->setChecked(b);

    const TQString soundFile = announceconfig->readPathEntry("SoundFile");
    if (!soundFile.isEmpty())
    {
        int pos = findInSound_List(soundFile);
        if (pos != -1) sound_list->setSelected(pos,true);
        else {
            addToSound_List(soundFile);
            sound_list->setSelected(sound_list->count()-1,true);
        }
    } else { sound_list->setSelected(0,true); }

    // Activate things according to configuration
    soundOnOff();

	emit changed(false);
}

void KSoundPageConfig::save() {

    config->setGroup("ktalkd");
    config->writePathEntry("ExtPrg", extprg_edit->lineEdit()->text());
    config->sync();
    announceconfig->setGroup("ktalkannounce");
    announceconfig->writePathEntry("talkprg", client_edit->lineEdit()->text());
    announceconfig->writeEntry("Sound", sound_cb->isChecked());
    announceconfig->writePathEntry("SoundFile",sound_list->text(sound_list->currentItem()));
    announceconfig->sync();
}

#include "soundpage.moc"
