using System;
using NeonScripting;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;

public class Script
{
			
	private static string htmlEncode(string inData, INeonScriptHost host)
	{
		return host.RemoteCalls.HtmlEncode(inData);
	}

	public bool Run(INeonScriptHost host)
	{
		var outputFolder = host.RemoteCalls.SelectFolder();
		if (outputFolder == "")
			return false;
		var outputFilename = Path.Combine(outputFolder, "albumlist.html");
		var imageFolder = Path.Combine(outputFolder, "_images");
		if (!Directory.Exists(imageFolder))			
			 Directory.CreateDirectory(imageFolder);
			 
		var sb = new StringBuilder();
		
		var albums = host.Albums;
		
		sb.AppendLine("<html>");
		sb.AppendLine("<head>");
		sb.AppendLine("<link rel=\"stylesheet\" href=\"styles.css\" type=\"text/css\">");
		sb.AppendLine("</head>");
		
		sb.AppendLine("<body>");
		
		sb.AppendLine("<table class=\"albums-table\">");

		var idx = 1;		
		foreach(var album in albums)
		{
			host.UpdateProgress(string.Format("Album {0}", idx));
			
			sb.AppendLine("<tr>");
			sb.AppendLine("<td>");
			var picture = album.AlbumPicturePath;
			if (string.IsNullOrEmpty(picture) || !File.Exists(picture))
			{
				picture = album.AlbumImage; // use cached miniature image
			}
			var currentExt = Path.GetExtension(picture);
			var imageName = Path.Combine(imageFolder, string.Format("alb_{0}{1}", album.AlbumId, currentExt));
			if (File.Exists(picture)) 
			{
				if (File.Exists(imageName))
					File.Delete(imageName);
				File.Copy(picture, imageName);
			}
			
			sb.AppendFormat("<img src=\"{0}\" width=\"160\"/>", imageName);
			sb.AppendLine("</td>");
			sb.AppendLine("<td>");
			sb.AppendFormat("<h2>{0}</h2>", htmlEncode(album.AggregatedAlbumName, host));
							
			sb.AppendLine("</td>");
			sb.AppendLine("</tr>");
			
			// Tracks from album
			var tracks = host.RemoteCalls.TracksInAlbum(album);
			sb.AppendLine("<tr>");
			sb.AppendLine("<td colspan=\"2\">");
			
			sb.AppendLine("<table class=\"albums-table\">");
			sb.AppendLine("<tr>");
			sb.AppendLine("<th>Artist</th>");
			sb.AppendLine("<th>Title</th>");
			sb.AppendLine("<th>Length</th>");
			sb.AppendLine("</tr>");
			
			foreach(var track in tracks)
			{
				sb.AppendLine("<tr>");
				sb.AppendFormat("<td>{0}</td>", track.Artist);
				sb.AppendFormat("<td>{0}</td>", track.Title);
				sb.AppendFormat("<td>{0}</td>", track.Songlength);
				sb.AppendLine("</tr>");
			}
			
			sb.AppendLine("</table>");
			
			
			
			sb.AppendLine("</td>");
			sb.AppendLine("</tr>");
			
			
			
			idx++;
		}
		sb.AppendLine("</table>");
		sb.AppendLine("</body>");
		sb.AppendLine("</html>");
		
		File.WriteAllText(outputFilename, sb.ToString());
		
		return true;
	}
}