/**
 * 
 */
package com.ejie.ab79.rest.util;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ejie.ab79.model.user.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

/**
 *  
 *
 */
public class AuthenticationUtil {

	private static final String TOKEN_BEARER_PREFIX = "Bearer ";
	private static final String SUPER_SECRET_KEY = "ab79BM";
	public static final String ERROR_TOKEN_INCORRECTO = "001";
	public static final String ERROR_TOKEN_VACIO = "002";
	public static final String ERROR_TOKEN_EXPIRADO = "003";
	
	
	public static void addAuthentication(Integer id, String user,String position, String uidSesion, String role){
		Collection<GrantedAuthority> grantedAuth=new HashSet<GrantedAuthority>();
		GrantedAuthority grant = new GrantedAuthorityImpl(role);
		grantedAuth.add(grant);
		
		User credentials=new User();
		credentials.setUserName(user);
		credentials.setPosition(position);
		credentials.setName(user);
		credentials.setUidSession(uidSesion);
		credentials.setId(id);
		
		SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, credentials,grantedAuth));
	}
	
	
	public static String getAuthentication(String token) {
		if (token != null) {
			
			Claims claims = validateToken(token);
			// Se procesa el token y se recupera el usuario.
			String user=claims.getSubject();
			Integer id=Integer.valueOf(claims.getId());
			if (user != null) {

				AuthenticationUtil.addAuthentication(id, user, "N/A", "N/A", "ROLE_USER");
				
				return user;
			}
			return null;
		}
		return null;
	}
	
	private static Claims validateToken(String token) {
 		String jwtToken = token.replace(TOKEN_BEARER_PREFIX, "");
		return Jwts.parser().setSigningKey(SUPER_SECRET_KEY.getBytes()).parseClaimsJws(jwtToken).getBody();
	}
}
