#include <wiisprite.h>
#include <set>
#include "imageloader.h"

using std::set;
using std::pair;

using namespace wsp;

Image *ImageLoader::get(const char *filename)
{
  string key(filename);
  map<string,Image*>::iterator it;
  it = imgs.find(key);
  if(it == imgs.end())
    return NULL;
  
  return it->second;
}

Image *ImageLoader::load(const char *filename)
{
  map<string,Image*>::iterator it;
  string key(filename);
  
  Image *newimg = new Image();
  if(newimg->LoadImage(filename)) {
    // failed to load
    delete newimg;
    it = imgs.find(key);
    if(it == imgs.end())
      return NULL;
    return it->second;
  }
  
  it = imgs.find(key);
  if(it != imgs.end()) {
    delete it->second;
    imgs.erase(it);
  }
  
  pair<string,Image*> pr(key,newimg);
  imgs.insert(pr);
  return newimg;
}

bool ImageLoader::reloadAll()
{
  map<string,Image*>::iterator it;
  set<string> toreload;
  set<string>::iterator sit;
  bool ret = true;

  for(it = imgs.begin(); it != imgs.end(); ++it)
    toreload.insert(it->first);
  
  for(sit = toreload.begin(); sit != toreload.end(); ++sit) {
    if(!this->load(sit->c_str()))
      ret = false;
  }
  
  return ret;
}

bool ImageLoader::release(const char *filename)
{
  string key(filename);
  map<string,Image*>::iterator it = imgs.find(key);
  bool ret = false;
  
  if(it != imgs.end()) {
    delete it->second;
    imgs.erase(it);
    ret = true;
  }
  
  return ret;
}

bool ImageLoader::releaseAll()
{
  map<string,Image*>::iterator it;
  for(it = imgs.begin(); it != imgs.end(); ++it)
    delete it->second;
  imgs.clear();
  
  return true;
}
