using System.Threading;

namespace PlayingWithServices.Core {
	public class AuthenticationService : IAuthenticationService {
		public AuthenticationService( IUserRepository repository ) {
			_repository = repository;
		}

		public bool CheckCredentials( string userName, string password ) {
			IUser user = _repository.FindBy( userName );
			if ( IsMatch( user.Password, password ) ) {
				ApplyPrincipalToThreadFor( user );
				return true;
			}
			return false;
		}

		private void ApplyPrincipalToThreadFor( IUser user ) {
			Thread.CurrentPrincipal = UserPrincipal.CreateFor( user );
		}

		private bool IsMatch( string expected, string actual ) {
			return string.Compare( expected, actual, false ) == 0;
		}

		private readonly IUserRepository _repository;
	}
}