using System;
using NeonScripting;
using System.Threading.Tasks;
using System.Collections;
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, "testlist.html");
		var imageFolder = Path.Combine(outputFolder, "_images");
		if (!Directory.Exists(imageFolder))			
			 Directory.CreateDirectory(imageFolder);
			 
		var sb = new StringBuilder();
		
		var tracks = host.Tracks;
		var groups = tracks.GroupBy(x => x.AlbumId).Select(y => y.ToList()).ToList();		
		
		sb.AppendLine("<html>");
		sb.AppendLine("<body>");
		sb.AppendLine("<table>");

		var idx = 1;		
		foreach(var album in groups)
		{
			host.UpdateProgress(string.Format("File {0}", idx));
			
			var albumId = album.First().AlbumId;
			var albumInfo = host.RemoteCalls.AlbumById(albumId);
			if (albumInfo != null)
			{
				sb.AppendLine("<tr>");
				sb.AppendLine("<td colspan=3>");
				var albumPicture = albumInfo.AlbumPicturePath;
				if (string.IsNullOrEmpty(albumPicture) || !File.Exists(albumPicture))
				{
					albumPicture = host.RemoteCalls.DefaultAlbumPicture;
				}
				var currentExt = Path.GetExtension(albumPicture);
				var imageName = Path.Combine(imageFolder, string.Format("alb_{0}{1}", albumId, currentExt));
				if (File.Exists(albumPicture)) 
				{
					if (File.Exists(imageName))
						File.Delete(imageName);
					File.Copy(albumPicture, imageName);
				}
				
				sb.AppendFormat("<img src=\"{0}\" width=\"256\"/>", imageName);
				sb.AppendFormat("<h2>{0}</h2>", htmlEncode(albumInfo.AggregatedAlbumName, host));
				sb.AppendLine("</td>");
				sb.AppendLine("<tr>");
				
				foreach(var track in album)
				{
					sb.AppendLine("<tr>");
					sb.AppendFormat("<td>{0}</td>", htmlEncode(track.Artist, host));
					sb.AppendLine("");
					sb.AppendFormat("<td>{0}</td>", htmlEncode(track.Title, host));
					sb.AppendLine("");
					sb.AppendFormat("<td>{0}</td>", htmlEncode(track.Album, host));
					sb.AppendLine("");
					sb.AppendLine("</tr>");
				}
			}
			idx++;
		}
		sb.AppendLine("</table>");
		sb.AppendLine("</body>");
		sb.AppendLine("</html>");
		
		File.WriteAllText(outputFilename, sb.ToString());
		
		return true;
	}
}