using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public class Genre
{
	private int id;
	private string name;

	public Genre(int id, string name)
	{
		this.id = id;
		this.name = name;
	}

	public int Id { get { return id; } }
	public string Name { get { return name; } }
}

public class Genres
{
	private SqlConnection connection;
	private SqlCommand command;
	private List<Genre> genres;

	public Genres()
	{
		connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MusicStoreDBConnection"].ConnectionString);
		command = new SqlCommand();
		command.Connection = connection;
		command.CommandType = CommandType.Text;
		connection.Open();
		genres = null;
	}

	private void Get()
	{
		command.CommandText = String.Format(CultureInfo.InvariantCulture, @"
SELECT [Id], [Name]
FROM [Genres]");

		genres = new List<Genre>();

		using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
		{					
			while (reader.Read())
			{
				genres.Add(new Genre(
					(int)reader["Id"],
					(string)reader["Name"]));
			}
		}
	}

	public List<string> GetNames()
	{
		if (null == genres)
		{
			Get();
			Debug.Assert(null != genres);
		}

		List<string> names = new List<string>();
		foreach (Genre g in genres)
		{
			names.Add(g.Name);
		}

		return names;
	}


	public int GetGenreId(string name)
	{
		if (null == genres)
		{
			Get();
			Debug.Assert(null != genres);
		}

		foreach (Genre g in genres)
		{
			if (string.Compare(name, g.Name, true, CultureInfo.InvariantCulture) == 0)
			{
				return g.Id;
			}
		}

		throw new IndexOutOfRangeException();
	}

}
