using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyTunes.Common.Entity;

namespace MyTunes.Library
{
    public partial class Playlists : System.Web.UI.Page
    {
        // private Parameter userParam = null;
        private ControlParameter filterParam = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            PlaylistSearchPager.GridView = PlaylistGridView;
            PlaylistSearchPager.Search += new SearchPagerControl.SearchEventHandler(PlaylistSearchPager_Search);
            SetGridFilter(User.Identity.Name, PlaylistSearchPager.Filter);
        }

        private void SetGridFilter(string username, string filter)
        {
            if (PlaylistDataSource.WhereParameters["UserName"]  == null)
                PlaylistDataSource.WhereParameters.Add(new Parameter("UserName", System.Data.DbType.String, username));
            PlaylistDataSource.Where = "UserName = @UserName";

            if (filter == null || filter.Length == 0)
            {
                if (PlaylistDataSource.WhereParameters.Contains(filterParam))
                    PlaylistDataSource.WhereParameters.Remove(filterParam);
            }
            else
            {
                if (filterParam == null)
                    filterParam = new ControlParameter("Filter", System.Data.DbType.String, "PlaylistSearchPager", "Filter");

                if (!PlaylistDataSource.WhereParameters.Contains(filterParam))
                    PlaylistDataSource.WhereParameters.Add(filterParam);

                PlaylistDataSource.Where += " && Title.Contains(@Filter)";
            }
        }

        void PlaylistSearchPager_Search(object sender, SearchEventArgs e)
        {
            SetGridFilter(User.Identity.Name, e.Filter);
        }

        protected int GetSongCount(object playlistID)
        {
            using (MyTunesDataContext db = new MyTunesDataContext())
            {
                return (from PlaylistItem in db.PlaylistItems
                        where PlaylistItem.PlaylistID == (int) playlistID
                        select PlaylistItem.PlaylistItemID).Count();
            }
        }

        protected string GetPlayLink(object playlistID)
        {
            return "~/Library/Play.aspx?playlistid=" + playlistID;
        }
    }
}