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

public class Script
{
	private INeonScriptHost _host;
	
	private bool playlistExists(string name)
	{
		var playlists = _host.RemoteCalls.Playlists;
		var pls = playlists.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
		return pls != null;
	}
	private string generatePlaylistName(string name)
	{
		var res = name;
		while (playlistExists(res))
		{
			res = "Copy of " + res;
		}
		return res;
	}
	public bool Run(INeonScriptHost host)
	{
		_host = host;
		var playlists = host.RemoteCalls.SelectFilesFromDialog();
		if (playlists.Count() == 0)
		{
			host.RemoteCalls.ShowMessage("No source playlists selected");
			return false;
		}
			
		var idx = 1;
		var filesToAdd = new List<string>();
		host.RemoteCalls.Log("Will process " + playlists.Count() + " playlists");
		foreach(var playlist in playlists)
		{
			host.RemoteCalls.Log("Processing playlist " + idx);
			host.UpdateProgress(string.Format("Reading playlist {0} of {1}", idx, playlists.Count()));
			var files = host.RemoteCalls.FilesInPlaylist(playlist);
			foreach(var file in files)
			{
				var trk = host.RemoteCalls.TrackFromFilename(file);
				if (trk == null)
					filesToAdd.Add(file);
			}
			idx++;
		}

		host.RemoteCalls.Log("Files to add " + filesToAdd.Count());
		if (filesToAdd.Count() > 0) 
		{
			host.UpdateProgress("Adding files to database");
			host.Database.AddFiles(filesToAdd);
		}
		host.RemoteCalls.Log("Added files");
	
		idx = 1;
		var tracksToAdd = new List<NeonScriptTrack>();
		foreach(var playlist in playlists)
		{
			host.RemoteCalls.Log("Processing playlist " + idx);
			host.UpdateProgress(string.Format("Creating playlist {0} of {1}", idx, playlists.Count()));
			tracksToAdd.Clear();
			var files = host.RemoteCalls.FilesInPlaylist(playlist);
			host.RemoteCalls.Log("Files in playlist: " + files.Count());
			foreach(var file in files)
			{
				var trk = host.RemoteCalls.TrackFromFilename(file);
				if (trk != null)
				{
					tracksToAdd.Add(trk);
				}
				else
				{
					Console.WriteLine("Track not found: " + file);
				}
			}

			var plsName = Path.GetFileNameWithoutExtension(playlist);
			plsName = generatePlaylistName(plsName);
			var pls = host.RemoteCalls.CreatePlaylist(plsName);
			host.RemoteCalls.AddToPlaylist(pls, tracksToAdd);
			idx++;
		}
		host.RemoteCalls.Log("All done");
		
		
		return true;
	}

}