/* This file is part of the KDE project
   Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "AFChoose.h"

#include <tqlabel.h>
#include <tqvbox.h>
#include <tqtextstream.h>
#include <tqdir.h>
#include <tqwhatsthis.h>

#include <tdelocale.h>
#include <ksimpleconfig.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kicondialog.h>

#include <KPrFactory.h>

AFChoose::AFChoose(TQWidget *parent, const TQString &caption, const char *name)
    : TQTabDialog(parent,name,true)
{
    setCaption(caption);
    setCancelButton(i18n("&Cancel"));
    setOkButton(i18n("&OK"));
    groupList.setAutoDelete(true);
    getGroups();
    setupTabs();
    connect(this,TQT_SIGNAL(applyButtonPressed()),this,TQT_SLOT(chosen()));
    connect(this,TQT_SIGNAL(cancelButtonPressed()),this,TQT_SLOT(cancelClicked()));
}

AFChoose::~AFChoose()
{
}

void AFChoose::getGroups()
{
    // global autoforms (as we don't have an editor we don't have local ones)
    TQString afDir = locate( "autoforms", ".autoforms", KPrFactory::global() );

    TQFile f( afDir );
    if ( f.open(IO_ReadOnly) ) {
        TQTextStream t( &f );
        TQString s;
        while ( !t.eof() ) {
            s = t.readLine();
            if ( !s.isEmpty() ) {
                grpPtr = new Group;
                TQString directory=TQFileInfo( afDir ).dirPath() + "/" + s.simplifyWhiteSpace();
                grpPtr->dir.setFile(directory);
                TQDir d(directory);
                if(d.exists(".directory")) {
                    KSimpleConfig config(d.absPath()+"/.directory", true);
                    config.setDesktopGroup();
                    grpPtr->name=config.readEntry("Name");
                }
                groupList.append( grpPtr );
            }
        }
        f.close();
    }
}

void AFChoose::setupTabs()
{
    if (!groupList.isEmpty())
    {
        for (grpPtr=groupList.first();grpPtr != 0;grpPtr=groupList.next())
        {
            grpPtr->tab = new TQVBox(this);
            TQWhatsThis::add(grpPtr->tab, i18n( "Choose a predefined shape by clicking on it then clicking the OK button (or just double-click on the shape). You can then insert the shape onto your slide by drawing the area with the mouse pointer." ) );
            grpPtr->loadWid = new TDEIconCanvas(grpPtr->tab);
            // Changes for the new TDEIconCanvas (Werner)
            TQDir d( grpPtr->dir.absFilePath() );
            d.setNameFilter( "*.desktop" );
            if( d.exists() ) {
                TQStringList files=d.entryList( TQDir::Files | TQDir::Readable, TQDir::Name );
                for(unsigned int i=0; i<files.count(); ++i) {
                    TQString path=grpPtr->dir.absFilePath() + TQChar('/');
                    files[i]=path + files[i];
                    KSimpleConfig config(files[i]);
                    config.setDesktopGroup();
                    if (config.readEntry("Type")=="Link") {
                        TQString text=config.readEntry("Name");
                        TQString icon=config.readEntry("Icon");
                        if(icon[0]!='/') // allow absolute paths for icons
                            icon=path + icon;
                        TQString filename=config.readPathEntry("URL");
                        if(filename[0]!='/') {
                            if(filename.left(6)=="file:/") // I doubt this will happen
                                filename=filename.right(filename.length()-6);
                            filename=path + filename;
                        }
                        grpPtr->entries.insert(text, filename);
                        // now load the icon and create the item
                        // This code is shamelessly borrowed from TDEIconCanvas::slotLoadFiles
                        TQImage img;
                        img.load(icon);
                        if (img.isNull()) {
                            kdWarning() << "Couldn't find icon " << icon << endl;
                            continue;
                        }
                        if (img.width() > 60 || img.height() > 60) {
                            if (img.width() > img.height()) {
                                int height = (int) ((60.0 / img.width()) * img.height());
                                img = img.smoothScale(60, height);
                            } else {
                                int width = (int) ((60.0 / img.height()) * img.width());
                                img = img.smoothScale(width, 60);
                            }
                        }
                        TQPixmap pic;
                        pic.convertFromImage(img);
                        TQIconViewItem *item = new TQIconViewItem(grpPtr->loadWid, text, pic);
                        item->setKey(text);
                        item->setDragEnabled(false);
                        item->setDropEnabled(false);
                    } else
                        continue; // Invalid .desktop file
                }
            }
            grpPtr->loadWid->setBackgroundColor(colorGroup().base());
            grpPtr->loadWid->setResizeMode(TQIconView::Adjust);
            grpPtr->loadWid->sort();
            connect(grpPtr->loadWid,TQT_SIGNAL(nameChanged(TQString)),
                    this,TQT_SLOT(nameChanged(TQString)));
            connect(this, TQT_SIGNAL(currentChanged(TQWidget *)), this,
                    TQT_SLOT(tabChanged(TQWidget*)));
            connect(grpPtr->loadWid,TQT_SIGNAL( doubleClicked ( TQIconViewItem *)),this,
                    TQT_SLOT(slotDoubleClick()));
            grpPtr->label = new TQLabel(grpPtr->tab);
            grpPtr->label->setText(" ");
            grpPtr->label->setMaximumHeight(grpPtr->label->sizeHint().height());
            addTab(grpPtr->tab,grpPtr->name);
        }
    }
}

void AFChoose::slotDoubleClick()
{
    chosen();
    accept();
}

void AFChoose::nameChanged(TQString name)
{
    for (grpPtr=groupList.first();grpPtr != 0;grpPtr=groupList.next())
        grpPtr->label->setText(name);
}

void AFChoose::tabChanged(TQWidget *w) {

    for(grpPtr=groupList.first();grpPtr != 0;grpPtr=groupList.next()) {
        if(grpPtr->tab==w)
            grpPtr->label->setText(grpPtr->loadWid->getCurrent());
    }
}

void AFChoose::chosen()
{
    if (!groupList.isEmpty())
    {
        for (grpPtr=groupList.first();grpPtr != 0;grpPtr=groupList.next())
        {
            if (grpPtr->tab->isVisible() && !grpPtr->loadWid->getCurrent().isEmpty())
                emit formChosen(grpPtr->entries[grpPtr->loadWid->getCurrent()]);
            else
                emit afchooseCanceled();
        }
    }
}

void AFChoose::cancelClicked()
{
    emit afchooseCanceled();
}

void AFChoose::closeEvent ( TQCloseEvent *e )
{
    emit afchooseCanceled();
    TQTabDialog::closeEvent ( e );
}

#include "AFChoose.moc"
