package kr.co.uplus.ez.common.jwt;

import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtAuthHeaderFilter extends  JwtAuthFilter {
	@Autowired
	private JwtService jwtSvc;
	
	public JwtAuthHeaderFilter(JwtProperties jwtProps) {
		super(jwtProps);
	}


	@Override
	public String getToken(HttpServletRequest request) {
		log.info("uri : {}", request.getRequestURI().toString());
		// 1. 공통 헤더 체크
		HashMap<String, String> headerMap = new HashMap<String, String>();
		Enumeration<String> enumeration = request.getHeaderNames();
		if (enumeration != null) {
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				headerMap.put(name.toLowerCase(), request.getHeader(name));
			}
		}
		log.info("headerMap : {}",headerMap.toString());
		
		// 1. access token이 저장된 헤더 읽기
		String header = request.getHeader(jwtProps.getHeader().toLowerCase());
		
		//log.info("header authToken: {}" , header);
		// 2. 헤더 값 검사
		if(header == null || !header.startsWith(jwtProps.getPrefix())) {
			return null;
		}

		// 3. Authorization 헤더에서 토큰 추출
		return header.replace(jwtProps.getPrefix(), "");
	}

	@Override
	public void onValidateSuccess(HttpServletRequest request, HttpServletResponse response, Claims claims) {
//		jwtSvc.updatePrivateToken(response, claims);
		
	}

	@Override
	public void onValidateException(HttpServletRequest request, HttpServletResponse response, JwtException exception) {
		if (exception instanceof ExpiredJwtException) {
			//jwtSvc.destroyPrivateToken(request, response);
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		}
	}

}