/***************************************************************************
 *   Copyright (C) 2005-2006 Nicolas Hadacek <hadacek@kde.org>             *
 *   Copyright (C) 2003 Alain Gibaud <alain.gibaud@free.fr>                *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/
#include "project.h"

#include <ksimpleconfig.h>

#include "devices/list/device_list.h"
#include "progs/base/prog_group.h"
#include "global_config.h"
#include "tools/gputils/gputils_config.h"

bool Project::load(TQString &error)
{
  if ( _url.fileType()==PURL::Project ) return XmlDataFile::load(error);

  if ( !_url.exists() ) {
    error = i18n("Project file %1 does not exist.").arg(_url.pretty());
    return false;
  }
  PURL::Url tmp = _url;
  _url = _url.toFileType(PURL::Project);
  if ( _url.exists() && XmlDataFile::load(error) ) return true;
  TDEConfig *config = new KSimpleConfig(tmp.filepath(), false);

  config->setGroup("Files");
  TQStringList list = config->readListEntry("inputFiles");
  TQStringList::const_iterator it = list.begin();
  for (; it!=list.end(); ++it) addFile(PURL::Url(directory(), *it));

  config->setGroup("General");
  setVersion(config->readEntry("version", "0.1"));
  setDescription(config->readEntry("description", TQString()));

  config->setGroup("Assembler");
  TQString device = config->readEntry("target-device");
  if ( device=="*" ) device = GlobalConfig::programmerGroup().supportedDevices()[0]; // compatibility
  Compile::Config::setDevice(this, Device::lister().checkName(device));
  GPUtils::Config *gconfig = new GPUtils::Config(this);
  gconfig->setGPAsmWarningLevel(TQMIN(config->readUnsignedNumEntry("warn-level", 0), uint(GPUtils::Config::Nb_WarningLevels)));
  gconfig->setRawIncludeDirs(Tool::Category::Assembler, config->readEntry("include-dir", TQString()));
  gconfig->setRawCustomOptions(Tool::Category::Assembler, config->readEntry("other-options", TQString()));

  config->setGroup("Linker") ;
  TQString hexFormatString = config->readEntry("hex-format", HexBuffer::FORMATS[HexBuffer::IHX32]);
  for (uint i=0; i<HexBuffer::Nb_Formats; i++)
    if ( hexFormatString==HexBuffer::FORMATS[i] ) gconfig->setHexFormat(HexBuffer::Format(i));
  gconfig->setRawIncludeDirs(Tool::Category::Linker, config->readEntry("objs-libs-dir", TQString()));
  gconfig->setRawCustomOptions(Tool::Category::Linker, config->readEntry("other-options", TQString()));

  delete gconfig;
  delete config;
  return true;
}

PURL::UrlList Project::openedFiles() const
{
  PURL::UrlList files;
  TQStringList list = listValues("general", "opened_files", TQStringList());
  TQStringList::const_iterator it = list.begin();
  for (; it!=list.end(); ++it) {
    if ( PURL::Url::fromPathOrUrl(*it).isRelative() ) files += PURL::Url(directory(), *it);
    else files += PURL::Url::fromPathOrUrl(*it);
  }
  return files;
}
void Project::setOpenedFiles(const PURL::UrlList &list)
{
  clearList("general", "opened_files");
  PURL::UrlList::const_iterator it = list.begin();
  for (; it!=list.end(); ++it)
    appendListValue("general", "opened_files", (*it).relativeTo(directory()));
}

PURL::UrlList Project::absoluteFiles() const
{
  PURL::UrlList abs;
  TQStringList files = listValues("general", "files", TQStringList());
  TQStringList::const_iterator it = files.begin();
  for (; it!=files.end(); ++it) abs += PURL::Url::fromPathOrUrl(*it).toAbsolute(directory());
  return abs;
}
void Project::addFile(const PURL::Url &url)
{
  appendListValue("general", "files", url.relativeTo(directory()));
}
void Project::removeFile(const PURL::Url &url)
{
  removeListValue("general", "files", url.relativeTo(directory()));
}
void Project::clearFiles()
{
  clearList("general", "files");
}

TQString Project::toSourceObject(const PURL::Url &url, const TQString &extension, bool forWindows) const
{
  PURL::Url tmp;
  if ( extension.isEmpty() ) tmp = url.toFileType(PURL::Object);
  else tmp = url.toExtension(extension);
  return tmp.relativeTo(directory(), forWindows ? PURL::WindowsSeparator : PURL::UnixSeparator);
}

TQStringList Project::objectsForLinker(const TQString &extension, bool forWindows) const
{
  TQStringList objs;
  // objects files corresponding to src files
  PURL::UrlList files = absoluteFiles();
  PURL::UrlList::const_iterator it;
  for (it=files.begin(); it!=files.end(); ++it)
    if ( (*it).data().group==PURL::Source ) objs += toSourceObject(*it, extension, forWindows);
  // objects
  for (it=files.begin(); it!=files.end(); ++it)
    if ( (*it).fileType()==PURL::Object ) objs += (*it).relativeTo(directory(), forWindows ? PURL::WindowsSeparator : PURL::UnixSeparator);
  return objs;
}

TQStringList Project::librariesForLinker(const TQString &prefix, bool forWindows) const
{
  TQStringList libs;
  PURL::UrlList files = absoluteFiles();
  PURL::UrlList::const_iterator it;
  for (it=files.begin(); it!=files.end(); ++it)
    if ( (*it).fileType()==PURL::Library ) libs += prefix + (*it).relativeTo(directory(), forWindows ? PURL::WindowsSeparator : PURL::UnixSeparator);
  return libs;
}

TQString Project::version() const
{
  return Compile::Config::globalValue(this, "version", "0.1");
}
void Project::setVersion(const TQString &version)
{
  Compile::Config::setGlobalValue(this, "version", version);
}

Tool::OutputType Project::outputType() const
{
  return Tool::OutputType::fromKey(Compile::Config::globalValue(this, "output_type", Tool::OutputType(Tool::OutputType::Executable).key()));
}
void Project::setOutputType(Tool::OutputType type)
{
  Compile::Config::setGlobalValue(this, "output_type", type.key());
}

TQString Project::description() const
{
  return Compile::Config::globalValue(this, "description", TQString());
}
void Project::setDescription(const TQString &description)
{
  Compile::Config::setGlobalValue(this, "description", description);
}

PURL::Url Project::customLinkerScript() const
{
  TQString s = Compile::Config::globalValue(this, "custom_linker_script", TQString());
  return PURL::Url::fromPathOrUrl(s);
}
void Project::setCustomLinkerScript(const PURL::Url &url)
{
  Compile::Config::setGlobalValue(this, "custom_linker_script", url.filepath());
}

TQValueList<Register::TypeData> Project::watchedRegisters() const
{
  TQValueList<Register::TypeData> watched;
  TQStringList list = listValues("general", "watched_registers", TQStringList());
  TQStringList::const_iterator it;
  for (it=list.begin(); it!=list.end(); ++it) {
    Register::TypeData rtd = Register::TypeData::fromString(*it);
    if ( rtd.type()!=Register::Invalid ) watched.append(rtd);
  }
  return watched;
}
void Project::setWatchedRegisters(const TQValueList<Register::TypeData> &watched)
{
  clearList("general", "watched_registers");
  TQValueList<Register::TypeData>::const_iterator it;
  for (it=watched.begin(); it!=watched.end(); ++it)
    appendListValue("general", "watched_registers", (*it).toString());
}

TQValueList<uint> Project::bookmarkLines(const PURL::Url &url) const
{
  TQValueList<uint> lines;
  TQStringList list = listValues("editors", "bookmarks", TQStringList());
  TQStringList::const_iterator it;
  for (it=list.begin(); it!=list.end(); ++it) {
    TQStringList slist = TQStringList::split(",", *it);
    TQStringList::const_iterator sit = slist.begin();
    if ( sit==slist.end() || (*sit)!=url.kurl().url() ) continue;
    for (; sit!=slist.end(); ++sit) {
      bool ok;
      uint line = (*sit).toUInt(&ok);
      if (!ok) continue;
      lines.append(line);
    }
    break;
  }
  return lines;
}
void Project::setBookmarkLines(const PURL::Url &url, const TQValueList<uint> &lines)
{
  TQStringList list = listValues("editors", "bookmarks", TQStringList());
  TQStringList nlist;
  TQStringList::const_iterator it;
  for (it=list.begin(); it!=list.end(); ++it) {
    TQStringList slist = TQStringList::split(",", *it);
    TQStringList::const_iterator sit = slist.begin();
    if ( sit!=slist.end() && slist.count()>1 && (*sit)!=url.kurl().url() ) nlist += *it;
  }
  if ( lines.count()!=0 ) {
    TQStringList slist = url.kurl().url();
    TQValueList<uint>::const_iterator lit;
    for (lit=lines.begin(); lit!=lines.end(); ++lit) slist += TQString::number(*lit);
    nlist += slist.join(",");
  }
  setListValues("editors", "bookmarks", nlist);
}
