using System.Linq;
using System.Threading;
using MusicMetaTagger.Core.Model;
using MusicMetaTagger.Core.Queries;
using MusicMetaTagger.Core.Services;
using MusicMetaTagger.Core.Utility;

namespace MusicMetaTagger.Client.AllMusicGuide.Services.Searchers
{
	public class AlbumSearcher : ITrackSearcher
	{
		private readonly IMusicGuide _musicGuide;

		public AlbumSearcher(IMusicGuide musicGuide)
		{
			_musicGuide = musicGuide;
		}

		public event StatusHandler SearchStatusUpdate;

		public Track SearchTrack(TrackQuery trackQuery, CancellationToken canellationToken)
		{
			if (string.IsNullOrEmpty(trackQuery.AlbumTitle))
				return null;

			var albumResults = ScoreUtility.ScoreResults(_musicGuide.SearchAlbum, trackQuery.AlbumTitle);

			foreach (ScoreContainer<AlbumResult> album in albumResults.Take(10))
			{
				if (canellationToken.IsCancellationRequested)
					return null;

				var tracks = _musicGuide.GetAlbum(album.Obj.AlbumId).Tracks;
				var match = TrackSimilarity.MatchTrack(trackQuery, tracks);
				if (match != null) return match;
			}
			return null;
		}
	}
}