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

namespace MyTunes.Library
{
    public partial class Home : System.Web.UI.Page
    {
        List<int> _currPlaylistSongs;

        protected void Page_Load(object sender, EventArgs e)
        {
            SongSearchPager.GridView = SongGridView;
            SongSearchPager.Search += new SearchPagerControl.SearchEventHandler(SongSearchPager_Search);

            SetPlaylistUser(User.Identity.Name);
            SetGridFilter(SongSearchPager.Filter);
        }

        private void SetupCheckboxes()
        {
            CheckBox chk;

            // string variable to store "|" pipes separated client side ID of checkbox controls
            string chkboxIds = string.Empty;

            foreach (GridViewRow rowItem in SongGridView.Rows)
            {
                // FindControl function is used here to find the checkbox control placed inside the GridView column
                chk = (CheckBox)(rowItem.Cells[0].FindControl("chkSong"));

                // ClientID property returns the client side of the server control
                chkboxIds += chk.ClientID + "|";
            }

            if (chkboxIds.Length > 0)
            {
                // Remove the extra "|" character at the end of the string.
                chkboxIds = chkboxIds.Remove(chkboxIds.Length - 1, 1);

                // Add onclick event to the chkSelectAll checkbox inside the HeaderRow of GridView TemplateField Column
                ((CheckBox)SongGridView.HeaderRow.Cells[0].FindControl("chkAll")).Attributes.Add("onclick", "selectAll('" + chkboxIds + "',this);");
            }
            else
            {
                SongGridView.HeaderRow.Cells[0].FindControl("chkAll").Visible = false;
            }
        }

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

        private void SetGridFilter(string filter)
        {
            if (filter == null || filter.Length == 0)
            {
                SongViewDataSource.Where = null;
                SongViewDataSource.WhereParameters.Clear();
            }
            else
            {
                if (SongViewDataSource.WhereParameters.Count == 0)
                    SongViewDataSource.WhereParameters.Add(new ControlParameter("Filter", System.Data.DbType.String, "SongSearchPager", "Filter"));

                SongViewDataSource.Where = "Artist.Contains(@Filter)||Album.Contains(@Filter)||Title.Contains(@Filter)";
            }
            SongGridView.PageIndex = 0;
        }

        protected void SongSearchPager_Search(object sender, SearchEventArgs e)
        {
            SetGridFilter(e.Filter);
        }

        // NOTE: This slows things down a lot!
        protected String GetPlayURL(object url)
        {
            using (MyTunesDataContext db = new MyTunesDataContext())
            {
                int songID = (from Songs in db.Songs
                             where Songs.URL == (string)url
                             select Songs.SongID).First();
                return "~/Library/Play.aspx?id=" + songID;
            }
        }

        protected String GetPlayLink(object songID)
        {
            return "~/Library/Play.aspx?id=" + songID;
        }

        protected List<int> PlaylistSongs
        {
            get
            {
                if (_currPlaylistSongs == null)
                {
                    // Pull the selected playlist song ID's and cache
                    // it to speed up the SongInPlaylist method.
                    _currPlaylistSongs = new List<int>();

                    if (ddlPlaylists.SelectedItem != null)
                    {
                        using (MyTunesDataContext db = new MyTunesDataContext())
                        {
                            var songs = from PlaylistItem in db.PlaylistItems
                                        where PlaylistItem.PlaylistID == Convert.ToInt32(ddlPlaylists.SelectedValue)
                                        select new
                                        {
                                            PlaylistItem.SongID
                                        };

                            foreach (var s in songs)
                                _currPlaylistSongs.Add(s.SongID);

                        }
                    }
                }
                return _currPlaylistSongs;
            }
        }

        protected bool SongInPlaylist(object songID)
        {
            return PlaylistSongs.Contains((int)songID);
        }

        protected void btnAddToPlaylist_Click(object sender, EventArgs e)
        {
            using (MyTunesDataContext db = new MyTunesDataContext())
            {
                int added = 0;
                lblResults.Text = String.Empty;

                for (int i = 0; i < SongGridView.Rows.Count; i++)
                {
                    GridViewRow gvr = SongGridView.Rows[i];
                    CheckBox cb = (CheckBox) gvr.FindControl("chkSong");

                    if (cb.Checked &&
                        !PlaylistSongs.Contains((int)SongGridView.DataKeys[i].Value))
                    {
                        if (!AddToPlaylist(db, (int)SongGridView.DataKeys[i].Value))
                            break;
                        else
                            added++;
                    }
                }

                if (lblResults.Text == String.Empty)
                    lblResults.Text = string.Format("Added {0} songs to playlist.", added);
            }
        }

        private bool AddToPlaylist(MyTunesDataContext db, int songID)
        {
            var pli = new PlaylistItem();

            pli.PlaylistID = Convert.ToInt32(ddlPlaylists.SelectedValue);
            pli.SongID = songID;

            db.PlaylistItems.InsertOnSubmit(pli);

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                lblResults.Text = "Error: " + ex.Message;
            }
            return false;

        }

        protected void SongGridView_DataBound(object sender, EventArgs e)
        {
            SetupCheckboxes();
        }
    }
}