
#include <libsaria/tags.h>
#include <libsaria/print.h>

#include <taglib/tag.h>
#include <taglib/fileref.h>
using namespace TagLib;

#include <sstream>
using namespace std;

TrackTag::TrackTag()
{
}

TrackTag::TrackTag(const TrackTag &tag)
{
	filepath = tag.filepath;
	title    = tag.title;
	artist   = tag.artist;
	album    = tag.album;
	comment  = tag.comment;
	genre    = tag.genre;
	lenstr   = tag.lenstr;
	year     = tag.year;
	track    = tag.track;
	length   = tag.length;
	bitrate  = tag.bitrate;
	sample   = tag.sample;
	channels = tag.channels;
}

TrackTag::TrackTag(string file)
{
	Tag *tag;
	AudioProperties *prop;
	FileRef ref(file.c_str());

	if (ref.isNull())
		throw "Error tagging file: " + file;
	filepath = file;

	/* Extract tags */
	tag     = ref.tag();
	title   = tag->title().to8Bit();
	artist  = tag->artist().to8Bit();
	album   = tag->album().to8Bit();
	comment = tag->comment().to8Bit();
	genre   = tag->genre().to8Bit();
	year    = tag->year();
	track   = tag->track();

	/* Extract audio properties */
	prop     = ref.audioProperties();
	length   = prop->length();
	bitrate  = prop->bitrate();
	sample   = prop->sampleRate();
	channels = prop->channels();

	make_lenstr();
}

TrackTag::TrackTag(InFile &in)
{
	filepath = in.read_str();
	title    = in.read_str();
	artist   = in.read_str();
	album    = in.read_str();
	comment  = in.read_str();
	genre    = in.read_str();
	lenstr   = in.read_str();
	year     = in.read_ui();
	track    = in.read_ui();
	length   = in.read_int();
	bitrate  = in.read_int();
	sample   = in.read_int();
	channels = in.read_int();
}

TrackTag::~TrackTag()
{
}

void TrackTag::save(OutFile &out)
{
	out.write_str(filepath, false);
	out.write_str(title,    false);
	out.write_str(artist,   false);
	out.write_str(album,    false);
	out.write_str(comment,  false);
	out.write_str(genre,    false);
	out.write_str(lenstr,   false);
	out.write_ui(year,      false);
	out.write_ui(track,     false);
	out.write_int(length,   false);
	out.write_int(bitrate,  false);
	out.write_int(sample,   false);
	out.write_int(channels, true);
}
 
void TrackTag::make_lenstr()
{
	int minutes;
	int seconds;
	stringstream stream;

	/* Convert length into mm:ss format */
	minutes = length / 60;
	seconds = length - (minutes * 60);
	stream << minutes << ":";
	if (seconds < 10)
		stream << "0";
	stream << seconds;
	lenstr = stream.str();
}

unsigned int TrackTag::get_track()
{
	return track;
}

string TrackTag::get_title()
{
	return title;
}

string TrackTag::get_lenstr()
{
	return lenstr;
}

string TrackTag::get_artist()
{
	return artist;
}

string TrackTag::get_album()
{
	return album;
}

unsigned int TrackTag::get_year()
{
	return year;
}

string TrackTag::get_filepath()
{
	return filepath;
}
