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

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

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

public class PublicKey {


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

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

    private PublicKey(String clientId, DataBodyPubkeyResp data) {
        this.data.put(clientId, data);
    }

    public static PublicKey getInstance() {
        return instance;
    }

    public static PublicKey getInstance(String clientId, DataBodyPubkeyResp data) {
        if (!isValidStat(clientId))
            synchronized (PublicKey.class) {
                if (!isValidStat(clientId))
                    instance = new PublicKey(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).getValidDtim()) < Long.parseLong(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))))
            return false;

        return true;
    }


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

}
