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

namespace MusicMetaTagger.Client.AllMusicGuide.RemoteDataAccess.Parser
{
	public class TrackParser : ParserBase<Track>
	{
		public override Track Parse(XmlDocument xml)
		{
			var track = new Track();
			var settings = TrackScraper.Default;

			if (XpathMatch(xml, settings.TrackUrlXpath))
			{
				var trackUrl = XpathMatchString(xml, settings.TrackUrlXpath);
				track.TrackId = RegexCapture(trackUrl, settings.TrackUrlIdRegex);
			}

			track.TrackNumber = Convert.ToInt32(XpathMatchString(xml, settings.TrackNumberXpath));

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

			track.TrackTitle =
				XpathMatch(xml, settings.TitleXpath)
					? XpathMatchString(xml, settings.TitleXpath)
					: string.Empty;

			if (XpathMatch(xml, settings.ComposerXpath))
				track.Composer =
					String.Join(", ",
					            XpathMatchStringList(xml, settings.ComposerXpath).ToArray());

			track.PerformerIds = new List<string>();
			var performerIdXpath = settings.PerformerIdXpath;
			if (!XpathMatch(xml, settings.PerformerIdXpath))
				performerIdXpath = settings.PerformerIdAlternateXpath;

			if (XpathMatch(xml, performerIdXpath))
			{
				var performerIdsRaw = XpathMatchStringList(xml, performerIdXpath);
				foreach (var performerIdRaw in performerIdsRaw)
				{
					if (RegexMatch(performerIdRaw, settings.PerformerIdRegex))
						track.PerformerIds.Add(RegexCapture(performerIdRaw, settings.PerformerIdRegex));
				}
			}

			var timeString = XpathMatchString(xml, settings.TimeXpath);
			track.TrackLength = StringUtility.ConvertTimeSpan(timeString);

			return track;
		}
	}
}