/* -*- C++ -*-

Copyright (C) 2002 Francesco Bresciani <fbresciani@users.sourceforge.net>
This file is part of Kemistry

Kemistry 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, or (at your option)
any later version.

Kemistry 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 Kemistry; see the file COPYING.  If not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

#include "kfile_openbabel.h"

#include <kurl.h>
#include <klocale.h>
#include <kdebug.h>
#include <kgenericfactory.h>

#include <fstream>

//Open Babel headers
#include "data.h"
#include "mol.h"
#include "fileformat.h"
#include "kemistry-openbabel.h"

typedef KGenericFactory<OpenBabelPlugin> OpenBabelFactory;

K_EXPORT_COMPONENT_FACTORY(kfile_openbabel,
                           OpenBabelFactory("kfile_openbabel"));

OpenBabelPlugin::OpenBabelPlugin(QObject* parent,  const char* name,
                                 const QStringList &args)
    : KFilePlugin(parent, name,  args)
{
    kdDebug(7034)<<"Open Babel plugin constructor"<<endl;
    QStringList mimelist;
    Kemistry::getOBReadMimeTypes(mimelist);

    for (QStringList::Iterator it = mimelist.begin(); it != mimelist.end(); ++it)
        makeMimeTypeInfo(*it);

}


bool OpenBabelPlugin::readInfo(KFileMetaInfo &info, uint)
{
    kdDebug(7034) << "OpenBabelPlugin::readMimeTypeInfo(KFileMetaInfo&, uint)" << endl;

    KFileMetaInfoGroup group = appendGroup(info, "General");

    int atoms, bonds;
    OpenBabel::OBMol molecule;
    OpenBabel::OBFileFormat ff;

    QString filename = info.path();
    molecule.SetInputType(OpenBabel::extab.FilenameToType(const_cast<char*>(filename.latin1())));

    std::ifstream ifs;
    ifs.open(filename);

    bool result = ff.ReadMolecule(ifs, molecule);

    if (!result)
        return result;

    atoms = molecule.NumAtoms();
    bonds = molecule.NumBonds();

    appendItem(group, "Atoms",  atoms);
    appendItem(group, "Bonds",  bonds);

    return true;
}

void OpenBabelPlugin::makeMimeTypeInfo(const QString& mimetype)
{
    kdDebug(7034) << "OpenBabelPlugin::makeMimeTypeInfo(const QString&) called for mimetype " <<
              mimetype << endl;

    KFileMimeTypeInfo* info = addMimeTypeInfo(mimetype);
    KFileMimeTypeInfo::GroupInfo* group =
        addGroupInfo(info, "General",  i18n("General"));

    KFileMimeTypeInfo::ItemInfo* item;
    item = addItemInfo(group, "Atoms",  i18n("Atoms"), QVariant::Int);
    item = addItemInfo(group, "Bonds",  i18n("Bonds"), QVariant::Int);

}

#include "kfile_openbabel.moc"

