package com.eactive.eai.authserver.service;

import java.security.SecureRandom;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import javax.annotation.PostConstruct;

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

import com.eactive.eai.common.session.SessionManager;
import com.eactive.eai.common.session.SessionManagerForIgnite;

@Service
public class BearerTokenService {


	
	
    public String generateCAToken(String clientId, Long expiresIn, Set<String> scopeSet) {
    	

    	
        String token = UUID.randomUUID().toString();
        
        BearerTokenInfo CATokenInfo = new BearerTokenInfo();
        CATokenInfo.setClientId(clientId);
        CATokenInfo.setExpiresIn(expiresIn);
        CATokenInfo.setExpiresAt(expiresIn);
        CATokenInfo.setScopeSet(scopeSet);
        
        //CATokenStore.put(token, CATokenInfo);
        
        SessionManager.getInstance().putCAToken(token, CATokenInfo);
        
        return token;
    }

    public boolean validateCA(String token) {
    	BearerTokenInfo CATokenInfo = SessionManager.getInstance().getCAToken(token);
    	if (CATokenInfo == null) return false;
    	
    	if (CATokenInfo.isExpired()) {
    		SessionManager.getInstance().removeCAToken(token);
    		return false;
    	}else {
    		return true;
    	}
    }

    public String getClientIdFromCA(String token) {
    	BearerTokenInfo CATokenInfo = SessionManager.getInstance().getCAToken(token);
        return CATokenInfo.getClientId();
    }

//    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//    private static final SecureRandom secureRandom = new SecureRandom();
//
//    public static String generateTokenString(int length) {
//        // Java 8의 IntStream과 Collectors.joining을 사용한 효율적인 방법
//        return IntStream.range(0, length)
//                .map(i -> secureRandom.nextInt(CHARACTERS.length()))
//                .mapToObj(CHARACTERS::charAt)
//                .map(String::valueOf)
//                .collect(Collectors.joining());
//    }
}

