
#include <libsaria/print.h>
#include <libsaria/idle.h>
#include <libsaria/path.h>
#include <libsaria/tags.h>
#include <libsaria/files.h>
#include <libsaria/library.h>

#include "library.h"
#include "path.h"

static void queue_dir_scan(LibraryPath *lib_path, string scan_dir, bool end)
{
	ScanTask *task = new ScanTask(lib_path, scan_dir, end);
	libsaria_queue_task(task);
}

static void queue_lib_save()
{
	SaveTask *task = new SaveTask(libsaria_library_save);
	libsaria_queue_task_front(task);
}

void Library::add_path(string dir)
{
	path_map.insert( pair<string, LibraryPath>(dir, LibraryPath(dir)) );
}

void Library::update_path(string dir)
{
	map<string, LibraryPath>::iterator it;
	it = path_map.find(dir);
	if (it != path_map.end())
		it->second.update();
}

void LibraryPath::insert_track(ino_t inode, TrackTag & tag)
{
	file_map[inode] = tag;
}

void LibraryPath::update()
{
	queue_dir_scan(this, path, true);
}

ScanTask::ScanTask(LibraryPath *lib_path, string scan_dir, bool end)
{
	library = lib_path;
	dir     = scan_dir;
	end_dir = end;
}

ScanTask::~ScanTask()
{
}

void ScanTask::tag_file(file filepath)
{
	try {
		TrackTag tag(dir + "/" + filepath.name);
		library->insert_track(filepath.d_ino, tag);
	} catch (string message) {
		println(message);
	}
}

/*
 * 1) Read a directory
 * 2) Create and queue a new UpdateTask for each subdirectory
 * 3) Find tags for each music file
 */
void ScanTask::run_task()
{
	vector<file> files;
	vector<file> dirs;
	readdir(dir, files, dirs);

	for (unsigned int i = 0; i < files.size(); i++)
		tag_file(files[i]);

	for (unsigned int i = 0; i < dirs.size(); i++)
		queue_dir_scan(library, dir + "/" + dirs[i].name, i == dirs.size() - 1);

	if (end_dir == true) {
		print("Library path size: ");
		println(library->size());
		libsaria_refresh_library();
		queue_lib_save();
	}
}
