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

namespace MusicMetaTagger.Client.AllMusicGuide.RemoteDataAccess.Parser
{
	public class AlbumResultParser : ParserBase<AlbumResult>
	{
		public override AlbumResult Parse(XmlDocument xml)
		{
			var albumResult = new AlbumResult();
			var settings = AlbumResultScraper.Default;

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

			if (XpathMatch(xml, settings.InfoXpath))
			{
				var infoRaw = XpathMatchString(xml, settings.InfoXpath);
				if (RegexMatch(infoRaw, settings.YearRegex))
				{
					var year = RegexCapture(infoRaw, settings.YearRegex);
					int yearInt;
					if (Int32.TryParse(year, out yearInt))
						albumResult.Year = yearInt;
				}
				if (RegexMatch(infoRaw, settings.GenreRegex))
				{
					var genre = RegexCapture(infoRaw, settings.GenreRegex);
					albumResult.Genre = genre.Trim();
				}
			}

			if (XpathMatch(xml, settings.ArtistUrlXpath))
			{
				var artistId = XpathMatchString(xml, settings.ArtistUrlXpath);
				albumResult.ArtistId = RegexCapture(artistId, settings.ArtistUrIdRegex);
				albumResult.ArtistName = XpathMatchString(xml, settings.ArtistXpath);
			}
			else if (XpathMatch(xml, settings.ArtistNoUrlXpath))
			{
				albumResult.ArtistName = XpathMatchString(xml, settings.ArtistNoUrlXpath);
			}
			
			albumResult.AlbumTitle = XpathMatchString(xml, settings.TitleXpath);

			return albumResult;
		}
	}
}