// WideMargin. Simple fast bible software.
// Copyright (C) 2012  Daniel Hughes
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using WideMargin.MVCInterfaces;

namespace WideMargin.Database
{
	/// <summary>
	/// Provides access to search results
	/// </summary>
	public class SearchResult : BibleBarResult
	{
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name='queryText'>Query text.</param>
		public SearchResult(string queryText) 
			: base(queryText)
		{
		}
		
		/// <summary>
		/// Not implemented always throws exception, 
		/// instead call GetFirstPage
		/// </summary>
		/// <returns>never returns</returns>
		/// <param name='database'>not used</param>
		/// <exception cref='NotImplementedException'>
		/// Thrown always, call GetFirstPage to get search results
		/// </exception>
		public override IEnumerable<IVerse> GetVerses (BibleDatabase database)
		{
			throw new NotImplementedException();
		}
		
		/// <summary>
		/// Provides access to the first page of results.
		/// </summary>
		/// <returns>The first page.</returns>
		/// <param name='database'>Database.</param>
		public SearchPageResult GetFirstPage(BibleDatabase database)
		{
			if (QueryText.Contains (" in:"))
			{
				return GetFirstPageForFilteredSearch(database);
			}
			return database.SearchFirstPage(QueryText);	
		}
		
		/// <summary>
		/// Gets the first page filtered by book.
		/// </summary>
		/// <returns>The first page for filtered search.</returns>
		/// <param name='database'>Database</param
		private SearchPageResult GetFirstPageForFilteredSearch(BibleDatabase database)
		{
			string[] parts = QueryText.Split(new string[]{" in:"}, StringSplitOptions.None);
			string searchTerm = parts[0];
			string filter = parts[1];
			var bookList = BookList.Get();
			string book;
			if(bookList.IsBook(filter))
			{
				book = filter;
			}
			else if(!NameAbbreviationLookup.Get().TryLookup(filter, out book))
			{
				//not a valid filter so result a no result search.
				return new SearchPageResult(new IVerse[]{}, new Dictionary<string, int>(),10, 1, QueryText);
			}
			return database.SearchFirstPageFiltered(searchTerm, book);
		}
	}
}

