package com.scrumkin.ejb;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.rmi.CORBA.Util;

import com.scrumkin.jpa.GroupEntity;
import com.scrumkin.jpa.PermissionEntity;
import com.scrumkin.jpa.UserEntity;

/**
 * Session Bean implementation class AddUsersBean.
 */
@Stateless(mappedName = "addUsers")
public class AddUserBean implements AddUserBeanLocal, AddUserBeanRemote {

	String username;
	String password;
	String confirmPassword;
	String name;
	String email;
	String confirmEmail;
	List<String> groups;

	EntityManager em;

	public AddUserBean() {

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getConfirmEmail() {
		return confirmEmail;
	}

	public void setConfirmEmail(String confirmEmail) {
		this.confirmEmail = confirmEmail;
	}

	public List<String> getGroups() {
		return groups;
	}

	public void setGroups(List<String> groups) {
		this.groups = groups;
	}

	public String[] getAvailablePermissions() {
		TypedQuery<PermissionEntity> query = em.createNamedQuery(
				"PermissionEntity.findAll", PermissionEntity.class);
		List<PermissionEntity> permissions = (List<PermissionEntity>) query
				.getResultList();

		String[] permissionNames = new String[permissions.size()];
		for (int i = 0; i < permissions.size(); i++) {
			permissionNames[i] = permissions.get(i).getName();
		}

		return permissionNames;
	}

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 
	public void persistUser() throws InvalidGroupException {
//		persistUser(this);


		
		Collection<GroupEntity> userGroups = new ArrayList<>();
		for(String userGroup : groups) {
			GroupEntity group = (GroupEntity)em.createQuery("SELECT * FROM groups g WHERE g.name = :name")
	                .setParameter("name", userGroup).getSingleResult();
			if(group == null) {
				throw new InvalidGroupException();
			}
			else {
				userGroups.add(group);
			}		
		}
		
		UserEntity user = new UserEntity();
		user.setUsername(this.username);
		user.setPassword(hash(this.password));
		user.setName(this.name);
		user.setEmail(this.email);
		user.setGroups(userGroups);
		
		em.persist(user);
		em.flush();
		
	}

	public String hash(String string) {
		try {
			// Create MessageDigest and encoding for input String
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest(string.getBytes("UTF-8"));

			// Hash the Input String
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < hash.length; i++) {
				sb.append(Integer.toString((hash[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

}

@@ -343,40 +343,8 @@
 pe;%0A
-import javax.persistence.Query;%0A
 impo
@@ -419,37 +419,8 @@
 ery;
-%0Aimport javax.rmi.CORBA.Util;
 %0A%0Aim
@@ -2275,20 +2275,17 @@
 es;%0A%09%7D%0A%0A
-    
+%09
 @Transac
@@ -2336,17 +2336,16 @@
 RES_NEW)
- 
 %0A%09public
@@ -2399,12 +2399,13 @@
 n %7B%0A
-//
 %09%09
+// 
 pers
@@ -2420,20 +2420,16 @@
 this);%0A%0A
-%0A%09%09%0A
 %09%09Collec
@@ -2483,16 +2483,17 @@
 );%0A%09%09for
+ 
 (String 
@@ -2550,18 +2550,25 @@
 pEntity)
+ 
 em
+%0A%09%09%09%09%09
 .createQ
@@ -2624,24 +2624,12 @@
 %22)%0A%09
-                
+%09%09%09%09
 .set
@@ -2681,16 +2681,17 @@
 );%0A%09%09%09if
+ 
 (group =
@@ -2743,20 +2743,17 @@
 ();%0A%09%09%09%7D
-%0A%09%09%09
+ 
 else %7B%0A%09
@@ -2786,17 +2786,13 @@
 %09%09%09%7D
-%09%09
 %0A%09%09%7D%0A
-%09%09
 %0A%09%09U
@@ -2988,18 +2988,16 @@
 roups);%0A
-%09%09
 %0A%09%09em.pe
@@ -3023,18 +3023,16 @@
 lush();%0A
-%09%09
 %0A%09%7D%0A%0A%09pu
@@ -3077,65 +3077,8 @@
 y %7B%0A
-%09%09%09// Create MessageDigest and encoding for input String%0A
 %09%09%09M
@@ -3200,36 +3200,8 @@
 );%0A%0A
-%09%09%09// Hash the Input String%0A
 %09%09%09S

Add users.