/*
 *  Copyright (C) 2008 Kristian Kristola
 *
 *  This program is distributed under the terms of the
 *  GNU General Public License.
 *
 *  This file is part of Dave the Ordinary Spaceman.
 *
 *  Dave the Ordinary Spaceman 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 3 of the License, or (at your option) any later version.
 *
 *  Dave the Ordinary Spaceman 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 Dave the Ordinary Spaceman. If not, see
 *  <http://www.gnu.org/licenses/>.
 *
 */

#include "library.h"
#include "image.h"
#include <dirent.h>
#include <cassert>
#include <iostream>

using namespace std;

#if defined(__MACOS__) || defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#endif

Library lib;

bool Library::instantiated = false;

Library::Library()
{
  if (instantiated) throw;
  instantiated = true;
}

Library::~Library()
{
}

bool Library::load_everything()
{
  /*
  DIR *libdir = opendir("graphics");
  if (libdir == NULL)
    return false;

  dirent *entry;

  while (entry = readdir(libdir)) {

    char *name = entry->d_name;

  }

  closedir(libdir);
  */
  return true;
}

LibraryEntry *Library::get(string name)
{
  LibraryEntry *ent;

  if (entries.count(name) == 1)
    return entries[name];
  else {
    ent = load_file(name);
    entries[name] = ent;
  }

  //assert(ent);
  return ent;
}

Image *Library::operator[](string name)
{
  Image *img = dynamic_cast<Image *>(get(name));
  //assert(img);
  return img;
}

// Lataa tiedoston ja ottaa selville sen pathin ennen latausta.
// filenamessa annetaan pelkästään tiedoston nimi ilman pathia
LibraryEntry *Library::load_file(string filename)
{
  if (filename.length() < 5)
    return NULL;

  string base = filename.substr(0, filename.length() - 4);
  string ext  = filename.substr(filename.length() - 3, 3);

  // Kuvat
  if (ext == "jpg" || ext == "png") {

    Image *l = new Image();
    string ff;

#if defined(__MACOS__) || defined(__APPLE__)
    static unsigned char mac_name[1024];
    static CFBundleRef mainbundle = NULL;
    if (mainbundle == NULL)
      mainbundle = CFBundleGetMainBundle();
    if (mainbundle == NULL)
      goto bundle_over;
    CFStringRef mac_base = CFStringCreateWithBytes(NULL,
						   (const UInt8 *)(base.c_str()),
						   base.length(), kCFStringEncodingUTF8, false);
    CFStringRef mac_ext  = CFStringCreateWithBytes(NULL,
						   (const UInt8 *)(ext.c_str()),
						   ext.length(), kCFStringEncodingUTF8, false);
    assert(mainbundle);
    assert(mac_base);
    assert(mac_ext);
    CFURLRef path = CFBundleCopyResourceURL(mainbundle, mac_base, mac_ext, CFSTR("graphics"));
    if (path) {
      CFURLGetFileSystemRepresentation(path, true, mac_name, 1023);
      CFRelease(path);
      ff = (char *)(mac_name);

      if (l->load(ff, true))
	return l;
    }
    CFRelease(mac_base);
    CFRelease(mac_ext);
  bundle_over:
#endif

    // Tästä eteenpäin suoritetaan jos ollaan Linuxissa tai jos mäkissä bundlesta ei löytynyt haluttua juttua
    ff = "graphics/" + filename;
    if (l->load(ff, true))
      return l;

    // Tästä eteenpäin suoritetaan jos mistään ei löytynyt mitään ja ohjelma kaatuu assert failediin
    cerr << "Ei löytyny: " << ff << endl;
    delete l;
    return NULL;
  }

  return NULL;
}
