package com.hepl.tunefortwo.utils;

import java.security.Key;
import java.util.Date;
import java.util.Map;

import javax.crypto.SecretKey;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

@Component
public class JwtUtils {
	private String jwtSecrets ="9j7WszeA5eprDq2cFWYwRlK2oFz3xjHTGdyTzrRJVsRfPxPyWVa7wMvBn4nN9HLe";
	private SecretKey secretKey;

//	  @Value("${app.jwt.jwtExpirationMs}")
	  private int jwtExpirationMs=44546485;

//	  @Value("${app.jwt.jwtCookieName}")
	  private String jwtCookie="authentication";
	 


	//  public ResponseCookie generateJwtCookie() {
//	    String jwt = generateTokenFromUsername(username,role,userId,email);
//	    ResponseCookie cookie = ResponseCookie.from(jwtCookie, jwt).path("/api").maxAge(24 * 60 * 60).httpOnly(true).build();
//	    return cookie;
	//  }

	  public void secret (String key) {
		  jwtSecrets = key;
	  }
	 
	  public String generateTokenFromUsername(String username, String role, String userId, String email,String profile ) {
		    return Jwts.builder()
		            .setSubject(email)
		            .claim("role", role)    
		            .claim("id", userId) 
		            .claim("name", username)
		            .claim("profile", profile)
		            .claim("email", email)
		            .setIssuedAt(new Date())
		            .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
		            .signWith(key(), SignatureAlgorithm.HS256)
		            .compact();
		}

	  private Key key() {
	     
	      byte[] keyBytes = Decoders.BASE64.decode(jwtSecrets);
	      return Keys.hmacShaKeyFor(keyBytes);
	  }
	  public String generateTokenFromUsernamefromMap( String email,Map<String, Object> privillege) {
		    return Jwts.builder()
		            .setSubject(email)
		            .claim("userDetails", privillege)
		            .setIssuedAt(new Date())
		            .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
		            .signWith(key(), SignatureAlgorithm.HS256)
		            .compact();
		}
	  
	  public Claims extractClaims(String token) {
	        
	        byte[] keyBytes = Decoders.BASE64.decode(jwtSecrets);	        
	        this.secretKey = Keys.hmacShaKeyFor(keyBytes);	        
	        return Jwts.parserBuilder()
	                .setSigningKey(secretKey)
	                .build()
	                .parseClaimsJws(token)
	                .getBody();
	    }

}
