using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using MusicMetaTagger.Client.AllMusicGuide.Properties;
using MusicMetaTagger.Core.Model;
using MusicMetaTagger.Core.Utility;

namespace MusicMetaTagger.Client.AllMusicGuide.RemoteDataAccess.Parser
{
	public class ArtistDiscographyPageParser : ParserBase<List<ArtistDiscography>>
	{
		public override List<ArtistDiscography> Parse(XmlDocument xml)
		{
			var artistDiscographies = new List<ArtistDiscography>();
			var settings = ArtistDiscographyPageScraper.Default;

			if (XpathMatch(xml, settings.DiscographyXpath))
			{
				var releaseTypeStr = XpathMatchString(xml, settings.ReleaseTypeXpath);
				releaseTypeStr = RegexCapture(releaseTypeStr, settings.ReleaseTypeRegex);

				ReleaseType releaseType;
				switch (releaseTypeStr)
				{
					case "main":
						releaseType = ReleaseType.Album;
						break;
					case "singles":
						releaseType = ReleaseType.Single;
						break;
					case "compilations":
						releaseType = ReleaseType.Compilation;
						break;
					default:
						throw new ApplicationException("Unknown release type");
				}

				var discographyParser = new ArtistDiscographyParser(releaseType);
				artistDiscographies.AddRange(
					from albumXml in XpathMatchXmlList(xml, settings.DiscographyXpath)
					let album = discographyParser.Parse(albumXml)
					where album.Year > 0
					select album);

				var artistId = StringUtility.CleanId(XpathMatchString(xml, settings.ArtistIdXpath));
				var artistName = XpathMatchString(xml, settings.ArtistXpath);

				foreach (var artistDiscography in artistDiscographies)
				{
					artistDiscography.ArtistId = artistId;
					artistDiscography.ArtistName = artistName;
				}
			}
			return artistDiscographies;
		}
	}
}