package org.bench4q.master.domain.service;

import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.factory.UserFactory;
import org.bench4q.master.domain.repository.UserRepository;
import org.bench4q.master.helper.SessionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserService {
	private UserFactory userFactory;
	private UserRepository userRepository;
	public static byte NORAML_AUTHENTICATION = 0;
	public static byte SUPER_AUTHENTICATION = 1;

	private UserFactory getUserFactory() {
		return userFactory;
	}

	@Autowired
	private void setUserFactory(UserFactory userFactory) {
		this.userFactory = userFactory;
	}

	private UserRepository getUserRepository() {
		return userRepository;
	}

	@Autowired
	private void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@Autowired
	private void setSessionHelper(SessionHelper sessionHelper) {
	}

	public boolean register(String userName, String password, byte scope) {
		return this.getUserRepository().attatch(
				this.getUserFactory().createUser(userName, password, scope));
	}

	public boolean validateUser(String userName, String password,
			byte requiredScope) {
		if (!this.getUserRepository().isExist(
				this.getUserFactory().createUser(userName, password,
						requiredScope))) {
			return false;
		}
		User user = this.getUserRepository().getUser(userName);
		return isScopeMeet(user, requiredScope);
	}

	private boolean isScopeMeet(User user, byte requiredScope) {
		return user.getScope() >= requiredScope;
	}

	public boolean deleteUser(String userName) {
		return this.getUserRepository().detach(userName);

	}
}
