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

   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 <tqdir.h>
#include <tqdom.h>
#include <tqfile.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <kdialog.h>
#include <tdelocale.h>

KCMBeagleBackends::KCMBeagleBackends(TQWidget *parent, const char * )
    : TDECModule(parent, "kcmbeaglebackends")
{
    TQVBoxLayout* general_layout = new TQVBoxLayout( this, KDialog::spacingHint() );

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

    listview = new TDEListView(this);
    listview->addColumn(i18n("Backends"));
    listview->setResizeMode( TQListView::LastColumn );
    listview->setFullWidth( true );
    general_layout->addWidget(listview);
    connect(listview, TQT_SIGNAL(clicked(TQListViewItem*)), TQT_SLOT(changedValue()));

    load();
}

KCMBeagleBackends::~KCMBeagleBackends()
{
}

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

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

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

    TDEProcess *proc = new TDEProcess;
    connect(proc, TQT_SIGNAL(receivedStdout(TDEProcess *, char *, int)), TQT_SLOT(gotAvailableBackends(TDEProcess *, char *, int)));
    *proc << "beagled" << "--list-backends";
    if (!proc->start(TDEProcess::Block,TDEProcess::Stdout))
        kdError("Could not ask Beagle daemon for available backends.\n");

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

    emit changed( useDefaults );
}

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

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

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

TQStringList KCMBeagleBackends::readDisabledBackends()
{
    TQStringList disabledBackends;

    TQDomDocument doc( "mydocument" );
    TQFile file( TQDir::home().absPath()+"/.beagle/config/daemon.xml" );
    if ( !file.open( IO_ReadOnly ) )
        return disabledBackends;

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

    TQDomElement docElem = doc.documentElement();

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

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

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

  TQFile configFile( TQDir::home().absPath()+"/.beagle/config/daemon.xml" );

  TQDomDocument doc( TQString::null );
  TQDomElement root;

  if (configFile.exists()) {
    if ( !configFile.open( IO_ReadOnly ) )
      return false;

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

    root = doc.documentElement();

    TQDomNode n = root.firstChild();
    while( !n.isNull() ) {
        TQDomElement 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 );
  }

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

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

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

  configFile.remove();
  if ( !configFile.open( IO_WriteOnly ) )
    return false;

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

  return true;
}

#include "backends.moc"
