#include "stdafx.h"
#include "addon_downloader.h"


Addon_downloader::Addon_downloader()
:
_lookup_installed_addons(true)
{
}


Addon_downloader::~Addon_downloader()
{
}


void Addon_downloader::do_ensure_valid_state(std::string &err)
{
  Addon_proc_net::do_ensure_valid_state(err);

  if (!err.empty())
    return;
  else if (!_installed_addons)
    err= "Installed addons were not set.";
  else if (_guid.empty())
    err= "Addon GUID was not set.";
  else if (_version.empty())
    err= "Addon version was not set.";
}


void Addon_downloader::do_execute()
{
  download(_guid, _version, _version, _lookup_installed_addons);
}


void Addon_downloader::download(const std::string &guid, const std::string &min_ver, const std::string &max_ver, bool lookup_installed_addons)
{
  Addon *addon= NULL;

  // download only if not installed yet
  if (lookup_installed_addons && (addon= _installed_addons->find(guid, min_ver, max_ver)))
    return;

  // all required manifests have to be loaded before starting download
  addon= _cached_addons->find(guid, min_ver, max_ver);
  if (!addon)
    _log->throw_err("Failed to find required manifest in cache: " + Addon::range_version_name(guid, min_ver, max_ver) + ".");

  _log->push_info(addon->full_name());

  std::string cached_package_filepath= _cached_addons->storage_dir().path() + "/" + addon->package_filename();
  if (!File(cached_package_filepath).exists())
  {
    std::string temp_package_filepath= _temp_dir.path() + "/" + addon->package_filename();

    _fd->filepath(temp_package_filepath);
    _fd->log_filepath(temp_package_filepath + ".log");
    _fd->url(_url_base + "?addon_part=package&addon=" + guid + "&addon_version=" + addon->version.str() + _url_suffix);

    Addon_proc_net::download();

    // move file from temp dir to addons cache
    if (!File::rename(temp_package_filepath, cached_package_filepath))
      _log->throw_err("Failed to move file from " + File(temp_package_filepath).quoted_path() +
        " to " + File(cached_package_filepath).quoted_path() + ".");
  }

  // recursively download all dependencies
  for (Addon::Dependencies::const_iterator i= addon->dependencies.begin(), i_end= addon->dependencies.end(); i != i_end; ++i)
    download(i->guid, i->min_ver, i->max_ver, lookup_installed_addons);
}
