/***************************************************************************
                          kgallerydialog.cpp  -  description
                             -------------------
    begin                : mar abr 1 2003
    copyright            : (C) 2003 by Javier Campos
    email                : javi@asyris.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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kgallerydialog.h"

#include <kdebug.h>
#include <kconfig.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kio/netaccess.h>

#include <qlineedit.h>
//#include <q3listview.h>
#include <qsplitter.h>
#include <qdom.h>
#include <qfileinfo.h>

KGalleryDialog::KGalleryDialog(QWidget* parent, const char *name )
      : Ui::KGalleryDialogBase()
{
  configRead();
  setupUi(this);
}

KGalleryDialog::~KGalleryDialog()
{
}

/** Open keduca file. This function can open a remote or local url. */
bool KGalleryDialog::openFile(const KUrl &url) {
    QString tmpFile;
    bool returnval=false;
    if( KIO::NetAccess::download( url, tmpFile, this ) )
    {
        returnval=loadFile( tmpFile );
        if (returnval) {
            _currentURL = url;
            kDebug()<<"... load successful: "<<_currentURL.url()<<endl;
        }

        KIO::NetAccess::removeTempFile( tmpFile );
    }else
        kDebug()<<"FileRead::openFile(): download NOT successful: "<<url.url()<<endl;

    return returnval;
}

bool KGalleryDialog::loadFile( const QString &filename )
{
    QDomDocument doc("document.xml");

    QFile file(filename);

    if(!file.open(QIODevice::ReadOnly))
    {
        return false;
    }
    doc.setContent( &file );

    if( doc.doctype().name() != "educagallery" )
    { return false; }

    QDomElement docElem = doc.documentElement();
    QDomNode n = docElem.firstChild();

    kDebug()<<"... load attributes: "<< docElem.tagName() <<endl;
    
    QDomNodeList dnList = n.childNodes();
    for( unsigned int i = 0; i < dnList.count(); ++i)
    {
        QTreeWidgetItem *newItem = new QTreeWidgetItem(listDocuments);
        QDomElement serversNode = dnList.item(i).toElement();

        kDebug()<<"... load attributes: "<< serversNode.text() <<endl;
        
        newItem->setText( 0, serversNode.  text() );
        newItem->setText( 1, serversNode.attribute( "language" ) );
        newItem->setText( 2, serversNode.attribute( "category" ) );
        newItem->setText( 3, serversNode.attribute( "type" ) );
        newItem->setText( 4, serversNode.attribute( "author" ) );
        newItem->setText( 5, serversNode.attribute( "address" ) );
        newItem->setSelected(false);
    }

    file.close();

    return true;
}

/** Read servers */
void KGalleryDialog::configRead()
{
    //KConfig *appconfig = KGlobal::config().data();
    QStringList servers;
    QStringList ipservers;
    QStringList::Iterator it_ipservers;
        
    //appconfig->setGroup( "kgallerydialog" );
    //KConfigGroup appConfigGroup = KGlobal::config()->group("kgallerydialog");
    //_split->setSizes( appconfig->readIntListEntry("Splitter_size") );
    //line1->setSizes( appConfigGroup.readEntry<Int>("Splitter_size", 0) ); //NOTE This isn't being ported
    //QSize defaultSize(500,400);
    //resize( appconfig->readSizeEntry("Geometry", &defaultSize ) );
    //resize( appConfigGroup.readEntry<QSize>("Geometry", &defaultSize ) );//NOTE This isn't being ported
    
    //appconfig->setGroup("Galleries Servers");
    KConfigGroup appConfigGroup = KGlobal::config()->group("Galleries Servers");
    //servers    = appconfig->readListEntry ( "Servers" );
    servers = appConfigGroup.readEntry("Servers", QStringList());
    //ipservers  = appconfig->readListEntry ( "ServersIP" );
    ipservers = appConfigGroup.readEntry("ServersIP", QStringList());

    if( ipservers.count() == 0 )
      {
      servers.append( "KEduca Main Server" );
      ipservers.append( "http://keduca.sourceforge.net/gallery/gallery.edugallery" );
      }

    it_ipservers=ipservers.begin();
    for ( QStringList::Iterator it_servers = servers.begin(); it_servers != servers.end(); ++it_servers )
    {
      QTreeWidgetItem *newItem = new QTreeWidgetItem(listServers);
      newItem->setText(0,*it_servers);
      newItem->setText(1,*it_ipservers);
      newItem->setSelected(false);
      ++it_ipservers;
    }
}

/** Write servers lists */
void KGalleryDialog::configWrite()
{
    QStringList servers;
    QStringList ipservers;
    //KConfig *config = KGlobal::config();

    //config->setGroup( "kgallerydialog" );
    //config->writeEntry("Splitter_size", _split->sizes() );  //NOTE This isn't being ported
    //config->writeEntry("Geometry", size() );
    //config->sync();

    //config->setGroup("Galleries Servers");
    KConfigGroup appConfigGroup = KGlobal::config()->group("Galleries Servers");
    //QTreeWidgetItem *item = listServers->firstChild();
    int index=0;
    QTreeWidgetItem *item = listServers->topLevelItem(index);
    while (item) {
        servers.append( item->text(0) );
        ipservers.append( item->text(1) );
        item = listServers->topLevelItem(index);
    }
    appConfigGroup.writeEntry("Servers", servers);
    appConfigGroup.writeEntry("ServersIP", ipservers);

    appConfigGroup.sync();
}

/** No descriptions */
void KGalleryDialog::slotButtonAdd()
{
      if( (lineName->text()).isEmpty() || (lineAddress->text()).isEmpty() )
        {
        KMessageBox::sorry(this, i18n("You need to specify a server."));
        return;
        }
        
        QTreeWidgetItem *newItem = new QTreeWidgetItem(listServers);
        newItem->setText(0,lineName->text());
        newItem->setText(1,lineAddress->text());
        newItem->setSelected(false);              
}

/** Open selected document */
void KGalleryDialog::accept()
{
    if (getURL().isEmpty())
      KMessageBox::sorry(this, i18n("You need to specify the file to open."));
    else
    {
      configWrite();
      QDialog::accept();
    }    
//    done( QDialog::Accepted );
}

/** Select Server */
void KGalleryDialog::slotServerSelected( QTreeWidgetItem *item )
{
    if (!item)
        return;

    KUrl url_server = KUrl( item->text(1) );

    listDocuments->clear();
    openFile( url_server );
}

/** Get keduca test url */
KUrl KGalleryDialog::getURL()
{
  QTreeWidgetItem *item = listDocuments->currentItem();

  if (!item)
    return KUrl();

  QString urlAddress = item->text(5);
    
  if( _currentURL.isLocalFile() && !KUrl(urlAddress).isValid() )
    {
    if( !QFileInfo(urlAddress).exists() )
      urlAddress = _currentURL.directory(KUrl::IgnoreTrailingSlash) + urlAddress;
    kDebug()<< "Imagen en local" <<endl;
    } else if( !_currentURL.isLocalFile() && !KUrl(urlAddress).isValid() )
       urlAddress = _currentURL.protocol() + "://" + _currentURL.host() + _currentURL.directory(KUrl::IgnoreTrailingSlash) + urlAddress;
    
  kDebug()<< urlAddress <<endl;
  return KUrl( urlAddress );
}

/** Add url */
void KGalleryDialog::putURL(const KUrl &urlFile)
{
        QTreeWidgetItem *newItem = new QTreeWidgetItem(listServers);
        newItem->setText( 1, urlFile.url() );
        newItem->setSelected(false);
}

#include "kgallerydialog.moc"
