using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace MyTunes
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["artist"] != null)
                MyTunesDatabase.FilterExpression = "artist_id = '" + Request.Params["artist"] + "'";

            if (!string.IsNullOrEmpty(txtAlbumFilter.Text))
                MyTunesDatabase.FilterExpression = "artist LIKE '%" + txtAlbumFilter.Text + "%'";

        }

        protected void btnFilterGo_Click(object sender, ImageClickEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtAlbumFilter.Text))
                MyTunesDatabase.FilterExpression = "album LIKE '%" + txtAlbumFilter.Text + "%'";
            else
                MyTunesDatabase.FilterExpression = null;

            AlbumGridView.DataBind();
        }

        protected string DisplayArtistName(object artistID)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = new SqlConnection(MyTunesDatabase.ConnectionString);
            cmd.CommandText = "SELECT artist FROM artist WHERE artist_id = '" + artistID.ToString() + "'";
            cmd.Connection.Open();

            return cmd.ExecuteScalar().ToString();
        }

        protected string DisplaySongCount(object albumID)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = new SqlConnection(MyTunesDatabase.ConnectionString);
            cmd.CommandText = "SELECT COUNT(*) FROM song WHERE album_id = '" + albumID.ToString() + "'";
            cmd.Connection.Open();

            return cmd.ExecuteScalar().ToString();
        }

        protected void AlbumGridView_DataBound(object sender, EventArgs e)
        {
            lblPageInfo.Text = string.Format("You are viewing page {0} of {1}...",
                AlbumGridView.PageIndex + 1, AlbumGridView.PageCount);

            lstPageSelect.Items.Clear();
            for (int i = 0; i < AlbumGridView.PageCount; i++)
            {
                ListItem pageItem = new ListItem(string.Concat("Page ", i + 1), i.ToString());
                lstPageSelect.Items.Add(pageItem);
                if (i == AlbumGridView.PageIndex)
                    pageItem.Selected = true;
            }
        }

        protected void lstPageSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            AlbumGridView.PageIndex = Convert.ToInt32(lstPageSelect.SelectedValue);
        }

        protected void AlbumGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Album")
            {
                Server.Transfer("Songs.aspx?album=" + e.CommandArgument);
            }
        }
    }
}