
#include <map>
#include <string>
using namespace std;

#include <libsaria/audio.h>
#include <libsaria/model.h>
#include <libsaria/callback.h>
#include <libsaria/library.h>
#include "library.h"

static map<string, LibraryPath> path_map;

map<string, LibraryPath> *get_library_map()
{
	return &path_map;
}

LibraryPath *get_library_path(string dir)
{
	map<string, LibraryPath>::iterator it;
	it = path_map.find(dir);
	if (it != path_map.end())
		return &it->second;
	return NULL;
}

void LibraryPath::for_each(libsaria::SourceModel *model)
{
	map<ino_t, TrackTag>::iterator it;

	for (it = file_map.begin(); it != file_map.end(); it++) {
		Track track = Track(it->first, &it->second);
		model->insert(track);
	}
}

void LibraryPath::get_info(void (*info_func)(struct libsaria::library::PathInfo &))
{
	struct libsaria::library::PathInfo info;
	info.path = path;
	info.size = size();
	info_func(info);
}

bool LibraryPath::get_info_id(ino_t &id, void (*func)(Track &))
{
	map<ino_t, TrackTag>::iterator it;
	it = file_map.find(id);
	if (it != file_map.end()) {
		Track track = Track(it->first, &it->second);
		func(track);
		return true;
	}
	return false;
}

bool LibraryPath::play_id(ino_t &id)
{
	map<ino_t, TrackTag>::iterator it;
	it = file_map.find(id);
	if (it == file_map.end())
		return false;
	libsaria::audio::load(it->second.get_filepath());
	return true;
}

namespace libsaria
{

	void library::for_each(SourceModel *model)
	{
		map<string, LibraryPath>::iterator it;
		for (it = path_map.begin(); it != path_map.end(); it++)
			it->second.for_each(model);
	}

	void library::for_each_path(void (*info_func)(struct library::PathInfo &))
	{
		map<string, LibraryPath>::iterator it;
		for (it = path_map.begin(); it != path_map.end(); it++)
			it->second.get_info(info_func);
	}

	void library::update()
	{
		map<string, LibraryPath>::iterator it;
		for (it = path_map.begin(); it != path_map.end(); it++)
			it->second.update();
	}

	void library::play_id(ino_t &id)
	{
		map<string, LibraryPath>::iterator it;
		for (it = path_map.begin(); it != path_map.end(); it++) {
			if (it->second.play_id(id) == true)
				break;
		}
	}

	bool library::get_info(ino_t &id, void (*func)(Track &))
	{
		bool found = false;
		map<string, LibraryPath>::iterator it;
		for (it = path_map.begin(); it != path_map.end(); it++) {
			if (it->second.get_info_id(id, func) == true) {
				found = true;
				break;
			}
		}
		return found;
	}

	unsigned int library::size()
	{
		unsigned int size = 0;
		map<string, LibraryPath>::iterator it;
		for (it = path_map.begin(); it != path_map.end(); it++)
			size += it->second.size();
		return size;
	}

	void library::refresh()
	{
		trigger_callback(LIBRARY_REFRESH);
	}

}; /* namespace: libsaria */
