package com.icontrols.oauth.utils;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Base64.Decoder;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icontrols.oauth.constants.CONSTANTS;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JWTUtils2 {
	private static final Logger logger = LoggerFactory.getLogger(JWTUtils2.class);

	public JWTUtils2() {
		super();
	}

//	// icontrols1793!@# base64인코딩하고앞에 난수(dlswmd) 붙임
//	public static String ACCESS_TOEKN_SECRET_KEY = "dlswmdaWNvbnRyb2xzMTc5MyFAIw==";
//	// icontrolsrefresh1793!@#
//	public static String REFRESH_TOKEN_SECRET_KEY = "aWNvbnRyb2xzcmVmcmVzaDE3OTMhQCM=";

	/**
	 * 
	 * @param token
	 * @return 
	 * @throws UnsupportedEncodingException
	 */
	public static boolean validateToken(String token) throws UnsupportedEncodingException {

		String secretKey = "";

		secretKey = CONSTANTS.ACCESS_TOEKN_SECRET_KEY;

		logger.info(token);
		Decoder decoder = Base64.getDecoder();
		// 시그니처가 맞는지 확인
		String enPayload = token.split("\\.")[1];
		String dePayload = new String(decoder.decode(enPayload));
		
		JSONObject obj = new JSONObject(dePayload);

		String jwt = Jwts.builder().claim("exp", obj.get("exp")) // 1시간 -> 설정정보로 변경해야함
				.claim("cmpIp", obj.get("cmpIp")).claim("homeId", obj.get("homeId")).claim("iat", obj.get("iat"))
				.signWith(SignatureAlgorithm.HS256, secretKey.getBytes("UTF-8")).compact();
		
		if (token.equals(jwt)) {
			long iat = Long.parseLong(obj.get("iat").toString());
			long currentTime = System.currentTimeMillis() / 1000;
			if (currentTime > iat + Long.parseLong(obj.get("exp").toString())) {
				return false;
			}
			return true;
		}
		return false;

	}
	/**
	 * 
	 * @param token
	 * @return 동/호
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 * @throws GeneralSecurityException
	 */

	public static String getHomeIdFromToken(String token)
			throws UnsupportedEncodingException, NoSuchAlgorithmException, GeneralSecurityException {

		Decoder decoder = Base64.getDecoder();
		String enPayload = token.split("\\.")[1];
		String dePayload = new String(decoder.decode(enPayload));
		JSONObject obj = new JSONObject(dePayload);

		String encodedHomeId = obj.get("homeId").toString();
		AES256Util aes = new AES256Util();
		String homeId = aes.decrypt(encodedHomeId);

		return homeId;
	}

}
