using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AddSongs : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
	protected void ButtonAddAlbum_Click(object sender, EventArgs e)
	{
		// Collect data from the textboxes.
		string albumName = TextBoxAlbumName.Text;
		string artistName = TextBoxArtistName.Text;
		string genre = DropDownList1.SelectedValue;
		string song1 = TextBoxSong1.Text;
		string song2 = TextBoxSong2.Text;
		string song3 = TextBoxSong3.Text;
		string song4 = TextBoxSong4.Text;		
		string coverArtFile = null;
		if (FileUpload1.HasFile)
		{
			// Get the file name;
			coverArtFile = FileUpload1.FileName;					
		}

		if (ValidateStrings(albumName, artistName, genre, song1, song2, song3, song4, coverArtFile))
		{			
			SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MusicStoreDBConnection"].ConnectionString);
			SqlTransaction transaction = null;
			SqlCommand command = new SqlCommand();
			command.Connection = connection;
			command.CommandType = CommandType.StoredProcedure;

			bool addedAlbumData = false;

			using (connection)
			{
				connection.Open();

				

				try
				{
					transaction = connection.BeginTransaction();
					command.Transaction = transaction;

					int albumId;

					command.CommandText = "AddAlbum";
					command.Parameters.Clear();
					command.Parameters.AddWithValue("@albumTitle", albumName);
					command.Parameters.AddWithValue("@artistName", artistName);
					command.Parameters.AddWithValue("@genreName", genre);
					command.Parameters.AddWithValue("@coverArtFile", coverArtFile);
					SqlParameter albumIdParam = new SqlParameter("@albumId", SqlDbType.Int);
					albumIdParam.Direction = ParameterDirection.Output;
					command.Parameters.Add(albumIdParam);

					command.ExecuteNonQuery();

					albumId = (int)albumIdParam.Value;

					List<string> songs = new List<string>();

					songs.Add(song1);
					songs.Add(song2);
					songs.Add(song3);
					songs.Add(song4);

					foreach (string song in songs)
					{
						// Only add songs that are not blank.
						if (!string.IsNullOrEmpty(song))
						{
							command.CommandText = "AddSong";
							command.Parameters.Clear();
							command.Parameters.AddWithValue("@songTitle", song);
							command.Parameters.AddWithValue("@albumId", albumId);
							SqlParameter songIdParam = new SqlParameter("@songId", SqlDbType.Int);
							songIdParam.Direction = ParameterDirection.Output;
							command.Parameters.Add(songIdParam);

							command.ExecuteNonQuery();
						}
					}
				}
				catch (SqlException se)
				{
					LabelStatus.Text = String.Format(
						"The album information could not be written to the database. The error message was: {0}",
						se.Message);
					LabelStatus.ForeColor = System.Drawing.Color.Red;

					if (null != transaction && null != transaction.Connection)
					{
						transaction.Rollback();
					}
				}
				finally
				{
					if (null != transaction && null != transaction.Connection)
					{
						// Commit the transaction.
						transaction.Commit();
						addedAlbumData = true;
					}
				}
			}

			// If all of the above succeeded, upload the image file.
			if (addedAlbumData)
			{

				// Form the full physical path for the location in which the file
				// will be saved. 
				string physicalPath = Request.PhysicalApplicationPath;
				physicalPath = Path.Combine(physicalPath, "images");
				physicalPath = Path.Combine(physicalPath, coverArtFile);

				FileUpload1.SaveAs(physicalPath);

				LabelStatus.Text = "Album added successfully.";
				LabelStatus.ForeColor = System.Drawing.Color.Green;
			}
		}
	}

	private bool ValidateStrings(
		string albumName,
		string artistName,
		string genre,
		string song1,
		string song2,
		string song3,
		string song4,
		string coverArtFile)
	{
		bool isValid = true;
		StringBuilder sb = new StringBuilder();
		sb.Append("Some fields in the form were not filled in. Please look at: \n");

		if (string.IsNullOrEmpty(albumName))
		{
			sb.Append("Album Name\n");			
			isValid = false;
		}

		if (string.IsNullOrEmpty(artistName))
		{
			if (!isValid) // Something is already in the list - need to add a comma.
			{
				sb.Append(", ");
			}
			sb.Append("Artist Name\n");
			isValid = false;
		}

		if (string.IsNullOrEmpty(song1) &&
			string.IsNullOrEmpty(song2) &&
			string.IsNullOrEmpty(song3) &&
			string.IsNullOrEmpty(song4))
		{
			if (!isValid) // Something is already in the list - need to add a comma.
			{
				sb.Append(", ");
			}
			sb.Append("Song Names (at least one song name must be filled in)\n");
			isValid = false;
		}

		if (string.IsNullOrEmpty(coverArtFile))
		{
			if (!isValid) // Something is already in the list - need to add a comma.
			{
				sb.Append(", ");
			}
			sb.Append("Cover art file\n");
			isValid = false;
		}

		if (!isValid)
		{
			LabelStatus.Text = sb.ToString();
			LabelStatus.ForeColor = System.Drawing.Color.Red;
		}

		return isValid;
	}
}
