/*****************************************************************

   Copyright (c) 2006 Stephan Binner <binner@kde.org>

   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; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.

******************************************************************/

#include "backends.h"

#include <QDir>
#include <qdom.h>
#include <QFile>
#include <QLabel>
#include <QLayout>
//Added by qt3to4:
#include <Q3VBoxLayout>
#include <kdialog.h>
#include <klocale.h>

KCMBeagleBackends::KCMBeagleBackends(const KComponentData &inst, QWidget *parent)
    : KCModule(inst, parent)
{
    Q3VBoxLayout* general_layout = new Q3VBoxLayout( this, KDialog::spacingHint() );

    general_layout->addWidget( new QLabel(i18n( "Select which of the available Beagle backends you want to have enabled." ), this) );

    listview = new K3ListView(this);
    listview->addColumn(i18n("Backends"));
    listview->setResizeMode( Q3ListView::LastColumn );
    listview->setFullWidth( true );
    general_layout->addWidget(listview);
    connect(listview, SIGNAL(clicked(Q3ListViewItem*)), SLOT(changedValue()));

    load();
}

KCMBeagleBackends::~KCMBeagleBackends()
{
}

void KCMBeagleBackends::changedValue()
{
    emit changed( true );
}

void KCMBeagleBackends::load()
{
    load( false );
}

void KCMBeagleBackends::load( bool useDefaults )
{
    listview->clear();

    K3Process *proc = new K3Process;
    connect(proc, SIGNAL(receivedStdout(K3Process *, char *, int)), SLOT(gotAvailableBackends(K3Process *, char *, int)));
    *proc << "beagled" << "--list-backends";
    if (!proc->start(K3Process::Block,K3Process::Stdout))
        kError("Could not ask Beagle daemon for available backends.");

    if (!useDefaults) {
        QStringList disabledBackends = readDisabledBackends();
        for ( QStringList::Iterator it_backends = disabledBackends.begin(); it_backends != disabledBackends.end(); ++it_backends ) {
            Q3ListViewItem *item = listview->findItem(*it_backends,0);
            if (item)
                ((Q3CheckListItem*)item)->setOn(false);
        }
    }

    emit changed( useDefaults );
}

void KCMBeagleBackends::defaults()
{
     load( true );
}

void KCMBeagleBackends::save()
{
   QStringList disabledBackends;
   Q3ListViewItemIterator it_items(listview);
   while (it_items.current())
   {
     if (!((Q3CheckListItem*)it_items.current())->isOn())
       disabledBackends << it_items.current()->text(0);
     it_items++;
   }
   saveDisabledBackends(disabledBackends);
}

void KCMBeagleBackends::gotAvailableBackends(K3Process*, char *buffer, int len)
{
    QString myBuf = QString::fromLatin1(buffer, len);
    if (myBuf.startsWith("User:")) {
      QStringList list = myBuf.split('\n');
      for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) 
        if ((*it).startsWith(" - ")) {
          Q3CheckListItem *item = new Q3CheckListItem(listview,(*it).mid(3),Q3CheckListItem::CheckBox);
          item->setOn(true);
        }
    }
}

QStringList KCMBeagleBackends::readDisabledBackends()
{
    QStringList disabledBackends;

    QDomDocument doc( "mydocument" );
    QFile file( QDir::home().absPath()+"/.beagle/config/daemon.xml" );
    if ( !file.open( QIODevice::ReadOnly ) )
        return disabledBackends;

    if ( !doc.setContent( &file ) ) {
        file.close();
        return disabledBackends;
    }
    file.close();

    QDomElement docElem = doc.documentElement();

    QDomNode n = docElem.firstChild();
    while( !n.isNull() ) {
        QDomElement e = n.toElement();
        if( !e.isNull() ) {
            if (e.tagName()=="DeniedBackends") {
               QDomNode ro = n.firstChild();
               while( !ro.isNull() ) {
                  QDomElement exel = ro.toElement();
                  if( !exel.isNull() )
                    disabledBackends << exel.text();
                  ro = ro.nextSibling();
                }
            }
        }
        n = n.nextSibling();
    }
    return disabledBackends;
}

bool KCMBeagleBackends::saveDisabledBackends(QStringList disabledBackends)
{
  QDir beagleDir(QDir::home().absPath()+"/.beagle");
  if (!beagleDir.exists())
    beagleDir.mkdir(QDir::home().absPath()+"/.beagle");

  QDir beagleConfigDir(QDir::home().absPath()+"/.beagle/config");
  if (!beagleConfigDir.exists())
    beagleConfigDir.mkdir(QDir::home().absPath()+"/.beagle/config");

  QFile configFile( QDir::home().absPath()+"/.beagle/config/daemon.xml" );

  QDomDocument doc( QString::null );
  QDomElement root;

  if (configFile.exists()) {
    if ( !configFile.open( QIODevice::ReadOnly ) )
      return false;

    if ( !doc.setContent( &configFile ) ) {
        configFile.close();
        return false;
    }
    configFile.close();

    root = doc.documentElement();

    QDomNode n = root.firstChild();
    while( !n.isNull() ) {
        QDomElement e = n.toElement();
        if( !e.isNull() )
            if (e.tagName()=="DeniedBackends")
              root.removeChild( e );
        n = n.nextSibling();
    }
  }
  else {
    doc.appendChild( doc.createProcessingInstruction(
                     "xml", "version=\"1.0\" encoding=\"UTF-8\"" ) );

    root = doc.createElement( "DaemonConfig" );
    root.setAttribute("xmlns:xsd","http://www.w3.org/2001/XMLSchema");
    root.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
    doc.appendChild( root );
  }

  QDomElement rootselement = doc.createElement( "DeniedBackends" );
  root.appendChild(rootselement);

  for ( QStringList::Iterator it = disabledBackends.begin(); it != disabledBackends.end(); ++it ) {
    QDomElement tag = doc.createElement( "anyType" );
    tag.setAttribute("xsi:type","xsd:string");
    rootselement.appendChild( tag );

    QDomText t = doc.createTextNode( *it );
    tag.appendChild( t );
  }

  configFile.remove();
  if ( !configFile.open( QIODevice::WriteOnly ) )
    return false;

  QTextStream stream( &configFile );
  stream << doc.toString();
  configFile.close();

  return true;
}

#include "backends.moc"
