
#include <ocarina/songlist.h>
#include "songlist.h"

SongList::SongList()  {}
SongList::~SongList() {}

static string columns[7] = { "Id", "#", "Title", "Length", "Artist", "Album", "Year" };
static int col_width[7]  = {    2,  20,     300,       60,      125,     125,     50 };

static GtkWidget *setup_label(string text)
{
	GtkWidget *label = gtk_label_new(text.c_str());
	gtk_label_set_angle(GTK_LABEL(label), 90);
	return label;
}

static GtkCellRenderer *setup_renderer()
{
	GtkCellRenderer *textcell = gtk_cell_renderer_text_new();
	gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(textcell), 1);
	return textcell;
}

static GtkListStore *setup_liststore()
{
	GtkListStore *liststore;
	liststore = gtk_list_store_new(7, G_TYPE_LONG, G_TYPE_INT, G_TYPE_STRING,
				       G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
				       G_TYPE_INT);
	return liststore;
}

static GtkWidget *setup_treeview(GtkListStore *liststore)
{
	GtkWidget *treeview = gtk_tree_view_new();

	GTK_CONNECT(treeview, "row-activated", songlist_row_activated, NULL);
	gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(treeview), TRUE);
	gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(liststore));
	return treeview;
}

static GtkWidget *setup_window(GtkWidget *treeview)
{
	GtkWidget *window = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(window),
				       GTK_POLICY_AUTOMATIC,
				       GTK_POLICY_AUTOMATIC);
	container_add(window, treeview);
	return window;
}

static void add_column(GtkCellRenderer *textcell, GtkWidget *treeview, int index)
{
	GtkTreeViewColumn *column  = gtk_tree_view_column_new_with_attributes(
					columns[index].c_str(), textcell,
					"text", index, NULL);
	gtk_tree_view_column_set_resizable(column, TRUE);
	gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED);
	gtk_tree_view_column_set_min_width(column, 2);
	gtk_tree_view_column_set_max_width(column, 700);
	gtk_tree_view_column_set_fixed_width(column, col_width[index]);
	gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column);
}

static void setup_columns(GtkCellRenderer *textcell, GtkWidget *treeview)
{
	for (unsigned int i = 0; i < 7; i++)
		add_column(textcell, treeview, i);
}

/*
 * I need an init() function to set up the scrolled window AFTER
 * the gtk_init() function has been called.  This allows the songlst
 * to be used as a static global variable in other files.
 */
void SongList::init(string text, SongListFuncs *funcs)
{
	/* Initialize helper variables */
	list_funcs = funcs;
	name = text;

	/* Set up the gtk widgets */
	label     = setup_label(name);
	textcell  = setup_renderer();
	liststore = setup_liststore();
	treeview  = setup_treeview(liststore);
	window    = setup_window(treeview);
	setup_columns(textcell, treeview);

	gtk_widget_show(label);
	gtk_widget_show_all(window);
}
