package cokr.xit.ens.modules.common.ctgy.nicedici.support.rest.utils;

import cokr.xit.ens.modules.common.ctgy.nicedici.support.rest.model.conf.DataBodyGenerateTokenResp;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class Token {


    private volatile static Token instance;
    private static Map<String, DataBodyGenerateTokenResp> data = new HashMap<>();

//    private PubkeyInfo() {
//
//    }
//
//    public static PubkeyInfo getInstance() {
//        if (instance == null)
//            synchronized (PubkeyInfo.class) {
//                if (instance == null)
//                    instance = new PubkeyInfo();
//            }
//
//        return instance;
//    }

    private Token(String clientId, DataBodyGenerateTokenResp data) {
        this.data.put(clientId, data);
    }

    public static Token getInstance() {
        return instance;
    }

    public static Token getInstance(String clientId, DataBodyGenerateTokenResp data) {
        if (!isValidStat(clientId))
            synchronized (Token.class) {
                if (!isValidStat(clientId))
                    instance = new Token(clientId, data);
            }

        return instance;
    }


    public static boolean isValidStat(String clientId) {
        if (instance == null)
            return false;
        if (data == null)
            return false;
        if (data.getOrDefault(clientId, null) == null)
            return false;
        if (Long.parseLong(data.get(clientId).getExpiredDt()) < Long.parseLong(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))))
            return false;

        return true;
    }


    public DataBodyGenerateTokenResp getData(String clientId) {
        return data.get(clientId);
    }

}
