/***************************************************************************
 *   Copyright (C) 2007 by Arnold Kraschinski                              *
 *   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 Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
 ***************************************************************************/

#include "kverbosuser.h"

// Standard C++ header files

// Qt-indlude files
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QStringList>
#include <QDomElement>
#include <QDomNodeList>

// KDE-include files
#include <kdebug.h>
#include <kstandarddirs.h>

QDomDocument            KverbosUser::m_userDom;
QDomNode                KverbosUser::m_activeUser;

KverbosUser::KverbosUser() {
}


KverbosUser::~KverbosUser() {
}

QStringList KverbosUser::groupNames() {
    if (m_userDom.isNull()) {
        readUserData();
    }
    QStringList groups;
    QDomNodeList g = groupnameNodes();
    int n = g.count();
    for (int i = 0; i < n; i++) {
        QDomElement e = g.at(i).toElement();
        if (!e.isNull()) {
            groups.append(e.text());
        }
    }
    return groups;
}

QStringList KverbosUser::userNames(QString groupName) {
    if (m_userDom.isNull()) {
        readUserData();
    }
    QStringList names;
    QDomNode group;
    QDomNodeList g = groupnameNodes();
    int n = g.count();
    for (int i = 0; i < n; i++) {
        QDomElement e = g.at(i).toElement();
        if ((!e.isNull()) && (e.text() == groupName)) {
            group = e.parentNode();
            break;
        }
    }
    if (!group.isNull()) {
        QDomElement ue = group.firstChildElement("user");
        if (!ue.isNull()) {
            QDomElement un = ue.firstChildElement("username");
            if (!un.isNull()) {
                names.append(un.text());
            }
            ue = ue.nextSiblingElement("user");
        }
    }
    return names;
}

bool KverbosUser::setUser(QString group, QString username) {
    if (m_userDom.isNull()) {
        readUserData();
    }
    QDomNodeList gn = groupnameNodes();
    int n = gn.count();
    QDomNodeList un = usernameNodes();
    int m = un.count();
    QDomNode node;
    for (int i = 0; i < n; i++) {
        QDomElement ge = gn.at(i).toElement();
        if ((!ge.isNull()) && (ge.text() == group)) {
            for (int j = 0; j < m; j++) {
                QDomElement ue = un.at(j).toElement();
                if ((!ue.isNull()) &&
                    (ue.text() == username) && 
                    (ge.parentNode() == ue.parentNode().parentNode()))
                {
                    node = un.at(j).parentNode();
                    kDebug() << "Found group: " << group << " and user: " << username << endl;
                }
            }
        }
    }
    if (!node.isNull()) {
        m_activeUser = node;
        return true;
    } else {
        m_activeUser.clear();
        return false;
    }
}

bool KverbosUser::userIsSet() {
    return !m_activeUser.isNull();
}

void KverbosUser::readUserData() {
    QFile f(KStandardDirs::locate("appdata", "data/userdata.xml"));
    if ( !f.open( QIODevice::ReadOnly ) ) {
        createUserData();
    } else {
        if ( !m_userDom.setContent( &f ) ) {
            createUserData();
        }
        f.close();
    }
}

void KverbosUser::saveUserData() {
    QString text = m_userDom.toString(4);
    QString fileName = KStandardDirs::locateLocal("appdata", "data/userdata.xml");
    QFile f( fileName );
    if ( !f.open( QIODevice::WriteOnly ) ) {
        kDebug() << "Could not write the user data! Missing permissions?" << endl;
    }
    QTextStream t( &f );
    t << text;
    f.close();
}

void KverbosUser::createUserData() {
    QString s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kverbos>";
    s += "<lastuser>";
    s += "    <hisname>default</hisname>";
    s += "    <hisgroup>default</hisgroup>";
    s += "</lastuser>";
    s += "<group>";
    s += "    <groupname>default</groupname>";
    s += "    <user>";
    s += "        <username>default</username>";
    s += "        <sessions>";
    s += "        </sessions>";
    s += "        <tenses>";
    s += "        </tenses>";
    s += "        <kvtmlfiles>";
    s += "            <f>spanish_verbs.kvtml</f>";
    s += "        </kvtmlfiles>";
    s += "        <verbselection>";
    s += "        </verbselection>";
    s += "    </user>";
    s += "</group>";
    s += "</kverbos>";
    if ( !m_userDom.setContent(s)) {
        kDebug() << "Could not create the basic user data in function createUserData." << endl;
    };	
}

QDomNodeList KverbosUser::groupnameNodes() {
    return m_userDom.documentElement().elementsByTagName("groupname");
}

QDomNodeList KverbosUser::usernameNodes() {
    return m_userDom.documentElement().elementsByTagName("username");
}
