#include "stdafx.h"
#include "addon.h"


//
// class Addon::Version
//


void Addon::Version::parse_str(const std::string &version_string)
{
  partials.clear();
  std::istringstream iss(version_string);
  int partial;
  while (iss >> partial)
  {
    partials.push_back(partial);
    iss.ignore(); // skip '.' symbol
  }
}


std::string Addon::Version::str() const
{
  std::ostringstream oss;
  for (Partials::const_iterator i= partials.begin(), i_end= partials.end(); i != i_end; ++i)
    oss << *i << '.';
  return oss.str().erase(oss.tellp() - (std::ostringstream::off_type) 1);
}


int Addon::Version::compare(const Version &version) const
{
  int res= 0;

  const Version *v1= (version.partials.size() < partials.size()) ? &version : this;
  const Version *v2= (v1 == this) ? &version : this;

  const Partials *vp1= &v1->partials;
  const Partials *vp2= &v2->partials;

  std::pair<Partials::const_iterator, Partials::const_iterator> diff_pair=
    std::mismatch(vp1->begin(), vp1->end(), vp2->begin());

  if (diff_pair.first != vp1->end())
    res= (*diff_pair.first < *diff_pair.second) ? -1 : 1;
  else
  {
    size_t vp1_size= vp1->size();
    size_t vp2_size= vp2->size();
    if (vp1_size != vp2_size)
      res= (vp1_size < vp2_size) ? -1 : 1;
  }

  if (this != v1)
    res*= -1;

  return res;
}


Addon::Version::operator std::string() const
{
  return str();
}


//
// class Addon
//


Addon::Addon()
:
_ext_info_loaded(false)
{
}


Addon::~Addon()
{
}


std::string Addon::range_version_name(const std::string &guid, const std::string &min_ver, const std::string &max_ver)
{
  return guid + " : " + (min_ver.empty() ? "*" : min_ver) + " - " + (max_ver.empty() ? "*" : max_ver);
}


std::string Addon::manifest_filename()
{
  return guid + "-" + version.str() + ".xml";
}


std::string Addon::package_filename()
{
  return guid + "-" + version.str() + ".zip";
}


std::string Addon::install_log_filename()
{
  return guid + "-" + version.str() + ".log";
}


void Addon::reset()
{
  name.clear();
  description.clear();
  date.clear();
  next_release_date.clear();
  release_notes.clear();
  type.clear();
  authorization= 0;
  _ext_info_loaded= false;

  dependencies.clear();
  menu_items.clear();
  root_folders.clear();
}


bool Addon::valid() const
{
  return !guid.empty() && !name.empty() && version.valid();
}


std::string Addon::full_name() const
{
  std::string res= name;
  if (version.valid())
    res+= (res.empty() ? "" : " v") + version.str();
  /*if (!date.empty())
    res+= (res.empty() ? "" : " date:") + date;*///!
  return res;
}
