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

namespace MyTunes.Library
{
    public partial class Play : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // First, determine if we are playing one song or an entire list
            if (Request.Params["id"] != null)
                PlaySong(Convert.ToInt32(Request.Params["id"]));
            else if (Request.Params["playlistid"] != null)
                PlayList(Convert.ToInt32(Request.Params["playlistid"]));
            else 
                lblError.Text = "Invalid Request: Please try again...";
        }

        /// <summary>
        /// Plays a single song by sending it directly to the browser/media player.
        /// </summary>
        /// <param name="songID">the ID of the song to play</param>
        private void PlaySong(int songID)
        {
            FileInfo info = null;

            try
            {
                // This is a hack that only seems to work for Internet Explorer
                // and Windows Media Player.
                //
                // Other options are:
                //
                // Build a local WPL (Windows PlayList) and send JavaScript code to
                // open a Windows Media Player window pointed to the WPL
                //
                // or perhaps
                //
                // Grab a copy of JavaLayer (Java MP3 Player) and embed the
                // Java Object inside a frame of this form or popup in window.

                using (MyTunesDataContext db = new MyTunesDataContext())
                {
                    if (Request.Params["id"] != null)
                    {
                        string url = (from Songs in db.Songs
                                      where Songs.SongID == Int32.Parse(Request.Params["id"])
                                      select Songs.URL).First();

                        if (url != null)
                        {
                            string filename = HttpUtility.UrlDecode(url);

                            // This can be used on a server by server basis
                            // to translate the database path name into the
                            // correct local path.  Just edit the web.config
                            // file's MusicPath and DatabasePath settings.
                            string databasePath = ConfigurationManager.AppSettings["DatabasePath"];
                            string musicPath = ConfigurationManager.AppSettings["MusicPath"];
                            string changeSlashes = ConfigurationManager.AppSettings["ChangeSlashes"];

                            if (databasePath != null && !databasePath.Equals(musicPath))
                                filename = filename.Replace(databasePath, musicPath);

                            if ("Yes".Equals(changeSlashes))
                                filename = filename.Replace("/", @"\");

                            info = new FileInfo(filename);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
                return;
            }

            if (info != null && info.Exists)
            {
                // Send back file directly to web browser, which
                // causes Internet Explorer to play the song

                Response.Clear();
                Response.ContentType = "audio/mp3";
                Response.WriteFile(info.FullName);
                Response.End();

            }
            else
            {
                lblError.Text = "Bad Request: Unable to play song(s).";
            }
        }

        private void PlayList(int playlistID)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(@"playlists\" + Session.SessionID));
            if (!dirInfo.Exists)
                dirInfo.Create();
            Random rnd = new Random();
            FileInfo playlistFile = null;
            do
            {
                playlistFile = new FileInfo(dirInfo.FullName + @"\" + rnd.Next().ToString() + ".asx");
            }
            while (playlistFile.Exists);

            StreamWriter stream = new StreamWriter(playlistFile.FullName, false);

            try
            {
                stream.WriteLine("<asx version=\"3.0\">");

                using (MyTunesDataContext db = new MyTunesDataContext())
                {
                    var playlists = from Playlist in db.Playlists
                                    where Playlist.PlaylistID == playlistID
                                    select Playlist;

                    if (playlists.Count() == 1)
                    {
                        stream.WriteLine(" <title>" + playlists.First().Name + "</title>");

                        var songs = from SongView in db.SongViews
                                    from PlaylistItem in db.PlaylistItems
                                    where SongView.SongID == PlaylistItem.SongID &&
                                        PlaylistItem.PlaylistID == playlistID
                                    select new
                                    {
                                        SongView.Artist,
                                        SongView.Title,
                                        SongView.SongID
                                    };
                        foreach (var s in songs)
                        {
                            stream.WriteLine(" <entry>");
                            stream.WriteLine("   <title>" + s.Artist + " - " + s.Title + "</title>");
                            stream.WriteLine("  <ref href=\"http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/Library/Play.aspx?id=" + s.SongID + "\"/>");
                            stream.WriteLine(" </entry>");
                        }

                        stream.WriteLine("</asx>");
                        stream.Close();
                    }
                    else
                    {
                        lblError.Text = "Bad Request: Playlist not found!";
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                File.Delete(playlistFile.FullName);
                lblError.Text = "Error: " + ex.Message;
                return;
            }
            finally
            {
                stream.Close();
            }


            Global g = (Global)HttpContext.Current.ApplicationInstance;

            g.TrackUserPlaylistFile(playlistFile.FullName);

            // Send back file directly to web browser, which
            // causes Internet Explorer to play the song

            Response.Clear();
            Response.ContentType = "audio/mp3";
            Response.WriteFile(playlistFile.FullName);
            Response.End();
        }
    }
}