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

static bool get_duration(gint64 &duration)
{
	GstFormat fmt = GST_FORMAT_TIME;
	return gst_element_query_duration(GST_ELEMENT(get_player()),
					  &fmt,
					  &duration);
}

static bool get_position(gint64 &position)
{
	GstFormat fmt = GST_FORMAT_TIME;
	return gst_element_query_position(GST_ELEMENT(get_player()),
					  &fmt,
					  &position);
}

namespace libsaria
{

	bool audio::seek_to(double prcnt)
	{
		bool ret;
		gint64 duration;

		ret = get_duration(duration);
		if (ret == true) {
			gst_element_seek_simple(GST_ELEMENT(get_player()),
						GST_FORMAT_TIME,
						GST_SEEK_FLAG_FLUSH,
						duration * prcnt);
		}
		return ret;
	}

	/* Use to seek forward or backward in a song */
	bool audio::seek(int dt)
	{
		bool ret;
		gint64 cur_pos;
		gint64 new_pos;

		ret = get_position(cur_pos);
		if (ret == true) {
			/* Convert seconds to nano-seconds */
			new_pos = cur_pos + (dt * GST_SECOND);
			if (new_pos < 0)
				new_pos = 0;
			gst_element_seek_simple(GST_ELEMENT(get_player()),
						GST_FORMAT_TIME,
						GST_SEEK_FLAG_FLUSH,
						new_pos);
		}
		return ret;
	}

	int audio::get_progress()
	{
		gint64 progress;
		gint64 duration;
		if (!get_position(progress))
			return 0;
		if (!get_duration(duration))
			return 0;
		return (progress * 100) / duration;
	}

};
