package cz.utb.tadis.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtUtil {

    @Autowired
    private JwtConfig jwtConfig;

    public String getToken(HttpServletRequest request){
        String token = null;
        String header = request.getHeader(jwtConfig.getHeader());
        if (header != null && header.startsWith(jwtConfig.getPrefix()))
            token = header.replace(jwtConfig.getPrefix(), "");
        return token;
    }


    public boolean isTokenValid(String token){
        try {
            Jwts.parser().setSigningKey(jwtConfig.getSecret()).parseClaimsJws(token);
            return true;
        }
        catch (Exception e){
            return false;
        }
    }

    public String generateToken(Authentication authentication) {
        UserSecurity user = (UserSecurity) authentication.getPrincipal();
        Date expirationDate = new Date(new Date().getTime() + jwtConfig.getExpirationMinutes()*60*1000);
        String token = Jwts.builder().setSubject(user.getUsername()).setIssuedAt(new Date()).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret()).compact();
        return token;
    }

    public String getEmailFromToken(String token){
        Claims claims = Jwts.parser().setSigningKey(jwtConfig.getSecret()).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }
}
