package com.dxhy.auth.runner;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import com.dxhy.auth.config.AuthConfig;
import com.dxhy.auth.config.KeyConfiguration;
import com.dxhy.common.jwt.RsaKeyHelper;
import com.dxhy.common.util.redis.RedisUtils;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:55:23
 *
 */
@Configuration
@Slf4j
public class AuthServerRunner implements CommandLineRunner {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private KeyConfiguration keyConfiguration;

    private static final String REDIS_USER_PRI_KEY = "DXHY:AUTH:JWT:PRI";
    private static final String REDIS_USER_PUB_KEY = "DXHY:AUTH:JWT:PUB";
    private static final String REDIS_SERVICE_PRI_KEY = "DXHY:AUTH:CLIENT:PRI";
    private static final String REDIS_SERVICE_PUB_KEY = "DXHY:AUTH:CLIENT:PUB";

    @Override
    public void run(String... args) throws Exception {
        if (redisUtils.hasKey(REDIS_USER_PRI_KEY) && redisUtils.hasKey(REDIS_USER_PUB_KEY)
            && redisUtils.hasKey(REDIS_SERVICE_PRI_KEY) && redisUtils.hasKey(REDIS_SERVICE_PUB_KEY)) {
            keyConfiguration.setUserPriKey(Base64.decode(redisUtils.get(REDIS_USER_PRI_KEY, -1)));
            keyConfiguration.setUserPubKey(Base64.decode(redisUtils.get(REDIS_USER_PUB_KEY, -1)));
            keyConfiguration.setServicePriKey(Base64.decode(redisUtils.get(REDIS_SERVICE_PRI_KEY, -1)));
            keyConfiguration.setServicePubKey(Base64.decode(redisUtils.get(REDIS_SERVICE_PUB_KEY, -1)));
        } else {
            Map<String, byte[]> keyMap = RsaKeyHelper.generateKey(AuthConfig.userSecret);
            keyConfiguration.setUserPriKey(keyMap.get("pri"));
            keyConfiguration.setUserPubKey(keyMap.get("pub"));
            redisUtils.set(REDIS_USER_PRI_KEY, Base64.encode(keyMap.get("pri")), -1);
            redisUtils.set(REDIS_USER_PUB_KEY, Base64.encode(keyMap.get("pub")), -1);
            keyMap = RsaKeyHelper.generateKey(AuthConfig.serviceSecret);
            keyConfiguration.setServicePriKey(keyMap.get("pri"));
            keyConfiguration.setServicePubKey(keyMap.get("pub"));
            redisUtils.set(REDIS_SERVICE_PRI_KEY, Base64.encode(keyMap.get("pri")), -1);
            redisUtils.set(REDIS_SERVICE_PUB_KEY, Base64.encode(keyMap.get("pub")), -1);

        }
    }
}
