/*
 *
 *    soniK digital audio editor
 *    Copyright (C) 2003-2006  Robert Walker <rob@tenfoot.org.uk>
 *
 *    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 "lrdfmanager.h"

#include <kstaticdeleter.h>
#include <kdebug.h>

#include <qdir.h>
#include <qstringlist.h>

#include <lrdf.h>

using Sonik::LrdfManager;

namespace
{
  static LrdfManager* lrdfInstance = 0;
  static KStaticDeleter<LrdfManager> lrdfDeleter;
}

LrdfManager::LrdfManager()
{
  lrdf_init();

  // TODO: custom search path
  QStringList searchPath;

  searchPath += "/usr/share/ladspa/rdf";
  searchPath += "/usr/local/share/ladspa/rdf";

  // load rdfs
  QStringList::Iterator path = searchPath.begin();
  for ( ; path != searchPath.end(); ++path)
  {
    QStringList rdfs = QDir(*path).entryList("*.rdf *.rdfs", QDir::Files);

    QStringList::Iterator r = rdfs.begin();
    for ( ; r != rdfs.end(); ++r)
      lrdf_read_file("file:" + *path + "/" + *r);
  }
}

LrdfManager::~LrdfManager()
{
  lrdf_cleanup();
}

LrdfManager& LrdfManager::instance()
{
  if (lrdfInstance == 0)
    lrdfDeleter.setObject(lrdfInstance, new LrdfManager);

  return *lrdfInstance;
}

LrdfManager::CategoryMap LrdfManager::categoryMap() const
{
  QMap<QString, QStringList> subclassMap;
  CategoryMap instanceMap;

  // walk the tree & categorize plugins
  QStringList classes = QString(LADSPA_BASE "Plugin");

  while (!classes.empty())
  {
    QString curClass = classes.front();
    classes.pop_front();

    QStringList& curCategory = subclassMap[curClass];

    lrdf_uris *subclasses = lrdf_get_subclasses(curClass.latin1());
    if (subclasses != NULL)
    {
      for (unsigned int i = 0; i < subclasses->count; i++)
      {
        QStringList subCategory = curCategory;
        subCategory.push_back(lrdf_get_label(subclasses->items[i]));
        subclassMap[subclasses->items[i]] = subCategory;
        classes.push_back(subclasses->items[i]);
      }
      lrdf_free_uris(subclasses);
    }

    lrdf_uris *instances = lrdf_get_instances(curClass.latin1());
    if (instances != NULL)
    {
      for (unsigned int i = 0; i < instances->count; i++)
        instanceMap[lrdf_get_uid(instances->items[i])] = curCategory;

      lrdf_free_uris(instances);
    }
  }

  return instanceMap;
}
