
namespace MasterDetailsWithRIAServices.Web.Services
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.ComponentModel.DataAnnotations;
	using System.Data;
	using System.Linq;
	using System.Web.DomainServices;
	using System.Web.DomainServices.Providers;
	using System.Web.Ria;
	using System.Web.Ria.Services;
	using MasterDetailsWithRIAServices.Web.Models;


	// Implements application logic using the ChinookEntities context.
	// TODO: Add your application logic to these methods or in additional methods.
	// TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
	// Also consider adding roles to restrict access as appropriate.
	// [RequiresAuthentication]
	[EnableClientAccess()]
	public class ChinookService : LinqToEntitiesDomainService<ChinookEntities>
	{

		// TODO: Consider
		// 1. Adding parameters to this method and constraining returned results, and/or
		// 2. Adding query methods taking different parameters.
		public IQueryable<Album> GetAlbums()
		{
			return this.ObjectContext.Album;
		}

		public void InsertAlbum(Album album)
		{
			this.ObjectContext.AddToAlbum(album);
		}

		public void UpdateAlbum(Album currentAlbum)
		{
			if ((currentAlbum.EntityState == EntityState.Detached))
			{
				this.ObjectContext.AttachAsModified(currentAlbum, this.ChangeSet.GetOriginal(currentAlbum));
			}
		}

		public void DeleteAlbum(Album album)
		{
			if ((album.EntityState == EntityState.Detached))
			{
				this.ObjectContext.Attach(album);
			}
			this.ObjectContext.DeleteObject(album);
		}

		// TODO: Consider
		// 1. Adding parameters to this method and constraining returned results, and/or
		// 2. Adding query methods taking different parameters.
		public IQueryable<Artist> GetArtists()
		{
			return this.ObjectContext.Artist
				.Where(artist => artist.Album.Count > 5)
				.OrderByDescending(artist => artist.Album.Count)
				;
		}

		public void InsertArtist(Artist artist)
		{
			this.ObjectContext.AddToArtist(artist);
		}

		public void UpdateArtist(Artist currentArtist)
		{
			if ((currentArtist.EntityState == EntityState.Detached))
			{
				this.ObjectContext.AttachAsModified(currentArtist, this.ChangeSet.GetOriginal(currentArtist));
			}
		}

		public void DeleteArtist(Artist artist)
		{
			if ((artist.EntityState == EntityState.Detached))
			{
				this.ObjectContext.Attach(artist);
			}
			this.ObjectContext.DeleteObject(artist);
		}

		public IQueryable<Album> GetAlbumsForArtistId(int artistId)
		{
			return this.ObjectContext.Album
				.Where(album => album.Artist.ArtistId == artistId)
				.OrderBy(album => album.AlbumId); // OrderBy to workaround an issue with EntityFramework.
		}

	}
}


