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

namespace MusicMetaTagger.Client.AllMusicGuide.RemoteDataAccess.Parser
{
	public class ArtistDiscographyParser : ParserBase<ArtistDiscography>
	{
		private readonly ReleaseType _releaseType;

		public ArtistDiscographyParser(ReleaseType releaseType)
		{
			_releaseType = releaseType;
		}

		public override ArtistDiscography Parse(XmlDocument xml)
		{
			var artistDiscography = new ArtistDiscography();
			var settings = ArtistDiscographyScraper.Default;

			var albumUrl = XpathMatchString(xml, settings.AlbumUrlXpath);
			artistDiscography.AlbumId = RegexCapture(albumUrl, settings.AlbumUrlIdRegex);

			var year = XpathMatchString(xml, settings.YearXpath);
			if (year.Length > 0 && StringUtility.IsNumeric(year))
				artistDiscography.Year = Convert.ToInt32(XpathMatchString(xml, settings.YearXpath));

			//rating
			if (XpathMatch(xml, settings.RatingXpath))
			{
				var ratingString = XpathMatchString(xml, settings.RatingXpath);
				if (!string.IsNullOrEmpty(ratingString))
				{
					ratingString = RegexCapture(ratingString, settings.RatingRegex);
					int rating;
					if (int.TryParse(ratingString, out rating))
						artistDiscography.Rating = Convert.ToInt32(rating);
				}
			}

			artistDiscography.Pick = XpathMatch(xml, settings.PickXpath);

			if (XpathMatch(xml, settings.LabelXpath))
				artistDiscography.Label = XpathMatchString(xml, settings.LabelXpath);

			artistDiscography.AlbumTitle = XpathMatchString(xml, settings.TitleXpath);

			artistDiscography.ReleaseType = _releaseType;
			// EPs will have "[EP]" after the title
			if (RegexMatch(artistDiscography.AlbumTitle, settings.ReleaseTypeRegex))
			{
				var releaseType = RegexCapture(artistDiscography.AlbumTitle, settings.ReleaseTypeRegex);
				if (releaseType == "EP")
					artistDiscography.ReleaseType = ReleaseType.EP;
			}
			else if (artistDiscography.AlbumTitle.Contains("Box Set"))
				artistDiscography.ReleaseType = ReleaseType.BoxSet;

			// TODO: add "has review"

			return artistDiscography;
		}
	}
}