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 WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ArtistGridView.Sort("artist", SortDirection.Ascending);
            }

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

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

            ArtistGridView.DataBind();
        }

        protected void txtArtistFilter_TextChanged(object sender, EventArgs e)
        {
            btnFilterGo_Click(null, null);
        }

        protected string DisplayAlbumCount(object artistID)
        {
            SqlCommand cmd = new SqlCommand();
            
            cmd.Connection = new SqlConnection(MyTunesDatabase.ConnectionString);
            cmd.CommandText = "SELECT COUNT(*) FROM album WHERE artist_id = '" + artistID.ToString() + "'";
            cmd.Connection.Open();

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

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

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

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

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

        }
    }
}