using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using LeafWeb.Core.Entities;

namespace LeafWeb.Core.DAL
{
	public class DataService : IDisposable
	{
		public static void RegisterInitializer()
		{
			Database.SetInitializer(new LeafWebInitializer());
			new LeafWebContext().Database.Initialize(true);
		}

		private readonly LeafWebContext _db = new LeafWebContext();

		public void Dispose()
		{
			_db.Dispose();
		}

		#region Fluxnet Sites

		public IQueryable<FluxnetSite> GetFluxnetSites()
		{
			return _db.FluxnetSites;
		}

		public IQueryable<FluxnetSite> GetFluxnetSitesAutocomplete(string term)
		{
			return 
				from fs in GetFluxnetSites()
				where fs.FluxnetId.StartsWith(term)
				|| fs.SiteName.Contains(term)
				select fs;
		}
		#endregion


		#region LeafInput Sites

		public IQueryable<LeafInput> GetLeafInputs()
		{
			return _db.LeafInputs;
		}

		public LeafInput GetLeafInput(int id)
		{
			return _db.LeafInputs.FirstOrDefault(li => li.Id == id);
		}

		public void AddLeafInput(LeafInput leafInput)
		{
			leafInput.Added = DateTime.Now;

			_db.LeafInputs.Add(leafInput);
			_db.SaveChanges();
		}

		#endregion

		public IQueryable<PhotosynthesisType> GetPhotosynthesisTypes()
		{
			return _db.PhotosynthesisTypes.OrderBy(pt => pt.SortOrder);
		}

		public PhotosynthesisType GetPhotosynthesisType(string id)
		{
			return _db.PhotosynthesisTypes.Find(id);
		}
	}
}
