/***************************************************************************
 *   Copyright (C) 2004 by Kraschinski Arnold                              *
 *   arnold.kra67@gmx.de                                                   *
 *                                                                         *
 *   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 Steet, Fifth Floor, Boston, MA 02110-1301, USA.           *
 ***************************************************************************/
#include "qmenu.h"

// Qt headera files
#include <QFile>
#include <QList>
#include <QStringList>
#include <QIcon>
#include <QPixmap>

#include <QDirIterator>
#include <QRegExp>

// KDE header files
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kdebug.h>

// project header files
#include "kverbossettings.h"

#define STEPSIZE   30

QMenu::QMenu( QWidget* parent )
: QTreeWidget ( parent ) {
    // div. configuration of the list view
    setColumnCount(3);
    setColumnWidth(0, 350);
    setColumnWidth(1, 200);
    setColumnWidth(2, 80);
    QStringList h;
    h.append(i18n("Topics"));
    h.append(i18n("Exercise File"));
    h.append(i18n("class"));
    setHeaderLabels(h);
    setIndentation(STEPSIZE);
    setSelectionBehavior(QAbstractItemView::SelectItems);
    setSelectionMode(QAbstractItemView::SingleSelection);
    QString lang = KVerbosSettings::translationLanguage();
    kDebug() << "language: " << lang;
    kDebug() << KStandardDirs::locate("appdata", "menu/menufile." + lang);
    m_menu = readMenufile( KStandardDirs::locate("appdata", "menu/menufile." + lang) );
    setMenu(m_menu);
    serachAdditionalExercises();
}

QMenu::~QMenu() {
}

bool QMenu::selected() {
    QList<QTreeWidgetItem *> items = selectedItems();
    return !items.empty();
}

QString QMenu::selectedFilename() {
    QList<QTreeWidgetItem *> items = selectedItems();
    if (items.empty())
        return "";
    else
        return items.first()->text(1);
}

QString QMenu::selectedClassname() {
    QList<QTreeWidgetItem *> items = selectedItems();
    if (items.empty())
        return "";
    else
        return items.first()->text(2);
}

void QMenu::setMenu(QDomDocument* menu)
{
    clear();
    QDomNode node = menu->firstChild();
    while ( !node.isNull()) {
        if ( node.isElement() && node.nodeName() == "menu") {
            buildTree(0, node.firstChild());
            break;
        }
        node = node.nextSibling();
    }
}

void QMenu::buildTree( QTreeWidgetItem* parentItem, const QDomNode parentNode ) {
    QTreeWidgetItem* thisItem = 0;
    QDomNode node = parentNode;
    while ( !node.isNull() ) {
        if ( node.isElement() && !node.nodeName().isEmpty() ) {
            QIcon icon;
            icon.addPixmap(KIconLoader::global()->loadIcon(node.toElement().attribute("img"), KIconLoader::Small));
            QStringList h;
            h.append(node.toElement().attribute("text"));
            h.append(node.toElement().attribute("file"));
            h.append(node.toElement().attribute("class"));
            if ( parentItem == 0 ) {
                thisItem = new QTreeWidgetItem(h);
                thisItem->setIcon(0, icon);
                addTopLevelItem(thisItem);
            } else {
                thisItem = new QTreeWidgetItem(h);
                thisItem->setIcon(0, icon);
                parentItem->addChild(thisItem);
            }
            buildTree( thisItem, node.toElement().firstChild() );
        }
        node = node.nextSibling();
    }
}

QDomDocument* QMenu::readMenufile( QString file ) {
    QDomDocument* m = new QDomDocument();
    QFile menuFile( file );
    if ( (!menuFile.open(QIODevice::ReadOnly)) || ( !m->setContent( &menuFile ) ) ){
        kDebug() << "Cannot open the menufile file." << endl;
        return 0;
    }
    menuFile.close();
    return m;
}

void QMenu::appendEntry( QDomNode menu, QDomNode entry )
{
    if ( ( menu.isNull() ) || ( entry.isNull() ) ) {
        return;
    }
    QDomNode entryNode = entry;
    while ( !entryNode.isNull() ) {
        bool isSibling = true;
        QDomNode menuNode = menu;
        QString nameEntry = entryNode.nodeName();
        QString textEntry = entryNode.toElement().attribute("text");
        QString classEntry = entryNode.toElement().attribute("class");
        QString fileEntry = entryNode.toElement().attribute("file");

        while ( !menuNode.isNull() ) {
            if ( menuNode.isElement() && entryNode.isElement() ) {
                QString nameMenu = menuNode.nodeName();
                QString textMenu = menuNode.toElement().attribute("text");
                QString classMenu = menuNode.toElement().attribute("class");
                QString fileMenu = menuNode.toElement().attribute("file");
                if ( (nameMenu == nameEntry) && (textMenu == textEntry) && 
                     (classMenu == classEntry) && (fileMenu == fileEntry) ) {
                    appendEntry ( menuNode.firstChild(), entryNode.firstChild() );
                    isSibling = false;
                }
            }
            menuNode = menuNode.nextSibling();
        }

        if ( isSibling ) {
            if ( !menu.parentNode().isNull() ) {
                QDomNode appendNode = entryNode;
                entryNode = entryNode.nextSibling();
                menu.parentNode().appendChild( appendNode );
            } else {
                kDebug() << "The parent node is NULL. That shouldn't happen here.";
            }
        } else {
            entryNode = entryNode.nextSibling();
        }
    }
}

void QMenu::serachAdditionalExercises()
{
    bool menuChanged = false;

    QDomNode startNodeMenu;
    QDomNode node = m_menu->firstChild();
    while ( !node.isNull()) {
        if ( node.isElement() && node.nodeName() == "menu") {
            startNodeMenu = node;
            break;
        }
        node = node.nextSibling();
    }

    KStandardDirs* dirs = KGlobal::dirs();
    QStringList list = dirs->findAllResources( "appdata", "exercises/*menu*" );
    for (QStringList::iterator it = list.begin(); it < list.end(); it++) {
        //kDebug() << "menu file --> " << *it;
        QString filename = *it;
        QRegExp regExp( "^(.*/)(.*)(.menu.)(.*)$" );
        if ( -1 < regExp.indexIn( filename ) ) {
            QStringList list = regExp.capturedTexts();
            QDomDocument* menuEntry = readMenufile( list[0] );
            if ( menuEntry != 0) {
                //kDebug() << "Add menu file: " << list[0];
                QDomNode startNodeNew;
                node = menuEntry->firstChild();
                while ( !node.isNull()) {
                    if ( node.isElement() && node.nodeName() == "menu") {
                        startNodeNew = node;
                        break;
                    }
                    node = node.nextSibling();
                }
                appendEntry( startNodeMenu.firstChild(), startNodeNew.firstChild() );
                menuChanged = true;
            }
            delete menuEntry;
        }
    }

    if ( menuChanged ) {
        setMenu ( m_menu );
    }
}


#include "qmenu.moc"
