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

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

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

			if (XpathMatch(xml, settings.YearXpath))
			{
				var yearRaw = XpathMatchString(xml, settings.YearXpath);
				if (RegexMatch(yearRaw, settings.YearRegex))
				{
					var year = RegexCapture(yearRaw, settings.YearRegex);
					int yearInt;
					if (Int32.TryParse(year, out yearInt))
						albumResult.Year = yearInt;
				}
			}

			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;
		}
	}

	public class SongParser : ParserBase<Song>
	{
		public override Song Parse(XmlDocument xml)
		{
			var song = new Song();
			var settings = SongScraper.Default;

			song.SongTitle = XpathMatchString(xml, settings.SongTitleXpath);
			var songUrlId = XpathMatchString(xml, settings.SongUrlIdXpath);
			song.SongId = RegexCapture(songUrlId, settings.SongUrlIdRegex);

			song.AppearsOnAlbum = new List<SongAppearsOnAlbum>();
			var songAppearsOnAlbumParser = new SongAppearsOnAlbumParser();

			if (XpathMatch(xml, settings.AlbumXpath))
			{
				var albumResultInfoXmlList = XpathMatchXmlList(xml, settings.AlbumXpath);
				song.AppearsOnAlbum.AddRange(albumResultInfoXmlList.Select(songAppearsOnAlbumParser.Parse));
				var i = 1;
				song.AppearsOnAlbum.ForEach(ar => ar.ResultOrder = i++);
			}

			return song;
		}
	}
}