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 AlbumParser : ParserBase<Album>
	{
		public override Album Parse(XmlDocument xml)
		{
			var album = new Album();
			var settings = AlbumScraper.Default;

			if (XpathMatch(xml, settings.ArtistUrlXpath))
			{
				var artistUrl = XpathMatchString(xml, settings.ArtistUrlXpath);
				album.ArtistId = RegexCapture(artistUrl, settings.ArtistUrlIdRegex);
				album.ArtistName = XpathMatchString(xml, settings.ArtistXpath);
			}
			else
			{
				album.VariousArtists = true;
				album.ArtistName = "Various Artists";
			}

			if (XpathMatch(xml, settings.SoundtrackXpath))
			{
				album.Soundtrack = true;
			}

			var albumId = XpathMatchString(xml, settings.AlbumIdXpath);
			album.AlbumId = StringUtility.CleanId(albumId);

			album.Title = XpathMatchString(xml, settings.TitleXpath);
			if (XpathMatch(xml, settings.ReleaseDateXpath))
				album.ReleaseDate = XpathMatchString(xml, settings.ReleaseDateXpath);

			//rating
			if (XpathMatch(xml, settings.RatingXpath))
			{
				float rating;
				if (float.TryParse(XpathMatchString(xml, settings.RatingXpath), out rating))
					album.Rating = Convert.ToInt32(rating*2);
			}

			if (XpathMatch(xml, settings.PickXpath))
				album.Pick = true;

			if (XpathMatch(xml, settings.CoverUrlXpath))
			{
				var coverUrl = XpathMatchString(xml, settings.CoverUrlXpath);
				album.CoverUrl = RegexCapture(coverUrl, settings.CoverUrlRegex);
			}
			if (XpathMatch(xml, settings.ReviewXpath))
				album.Review = XpathMatchString(xml, settings.ReviewXpath);

			if (XpathMatch(xml, settings.ReviewerXpath))
			{
				var reviewer = XpathMatchString(xml, settings.ReviewerXpath);
				album.Reviewer = RegexCapture(reviewer, settings.ReviewerRegex).Trim();
			}

			if (XpathMatch(xml, settings.StylesXpath))
				album.Styles = XpathMatchStringList(xml, settings.StylesXpath);
			if (XpathMatch(xml, settings.MoodsXpath))
				album.Moods = XpathMatchStringList(xml, settings.MoodsXpath);
			if (XpathMatch(xml, settings.ThemesXpath))
				album.Themes = XpathMatchStringList(xml, settings.ThemesXpath);

			album.Tracks = new List<Track>();

			if (XpathMatch(xml, settings.TrackXpath))
			{
				var trackParser = new TrackParser();
				var tracks =
					from tXml in XpathMatchXmlList(xml, settings.TrackXpath)
					let t = trackParser.Parse(tXml)
					where t.PerformerIds.Any() && t.TrackLength > TimeSpan.MinValue
					select t;

				foreach (var track in tracks)
				{
					track.AlbumId = album.AlbumId;
					album.Tracks.Add(track);
				}
			}
			return album;
		}
	}
}