
#include <libsaria/library.h>
#include "library.h"

Library::Library()
{
}

Library::~Library()
{
}

void Library::list_all(list<Track> &track_list)
{
	map<string, LibraryPath>::iterator it;
	for (it = path_map.begin(); it != path_map.end(); it++)
		it->second.list_all(track_list);
}

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

void Library::save()
{
	OutFile out("library.lib");
	map<string, LibraryPath>::iterator it;

	out.write_lui(path_map.size(), true);
	for (it = path_map.begin(); it != path_map.end(); it++)
		it->second.save(out);
}

void Library::load()
{
	unsigned int size;
	string dir;
	InFile in("library.lib");

	if (!in.good())
		return;
	size = in.read_lui();

	for (unsigned int i = 0; i < size; i++) {
		dir = in.read_str();
		path_map.insert(
			pair<string, LibraryPath>(dir, LibraryPath(in, dir))
		);
	}
}

void LibraryPath::save(OutFile &out)
{
	map<ino_t, TrackTag>::iterator it;

	out.write_str(path, false);
	out.write_lui(file_map.size(), true);
	for (it = file_map.begin(); it != file_map.end(); it++) {
		out.write_ino(it->first, false);
		it->second.save(out);
	}
}

LibraryPath::LibraryPath(InFile &in, string dir)
{
	unsigned int size;
	ino_t inode;

	path = dir;
	size = in.read_lui();
	println("Library path dir: " + path);
	print("Library path size: ");
	println(size);

	for (unsigned int i = 0; i < size; i++) {
		inode = in.read_ino();
		file_map[inode] = TrackTag(in);
	}
}
