package com.dxhy.auth.client.runner;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;

import com.dxhy.auth.client.config.ServiceAuthConfig;
import com.dxhy.auth.client.configuration.UserAuthConfig;
import com.dxhy.auth.client.feign.ServiceAuthFeign;
import com.dxhy.common.msg.BaseResponse;
import com.dxhy.common.msg.ObjectRestResponse;
import com.dxhy.common.util.redis.UserAuthConfiguration;

import lombok.extern.slf4j.Slf4j;

/**
 * 监听完成时触发
 *
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:52:20
 *
 */
@Configuration
@Slf4j

public class AuthClientRunner implements CommandLineRunner {
    @Resource
    private ServiceAuthConfig serviceAuthConfig;
    @Resource
    private UserAuthConfig userAuthConfig;
    @Resource
    private UserAuthConfiguration userAuthConfiguration;
    @Lazy
    @Resource
    private ServiceAuthFeign serviceAuthFeign;

    @Override
    public void run(String... args) {
        log.info("初始化加载用户pubKey");
        try {
            refreshUserPubKey();
        } catch (Exception e) {
            log.error("初始化加载用户pubKey失败,1分钟后自动重试!", e);
        }
        log.info("初始化加载客户pubKey");
        try {
            refreshServicePubKey();
        } catch (Exception e) {
            log.error("初始化加载客户pubKey失败,1分钟后自动重试!", e);
        }
    }

    @Scheduled(cron = "0 0/30 * * * ?")
    public void refreshUserPubKey() {
        if (serviceAuthConfig.isAuthClientStatus()) {
            BaseResponse resp =
                serviceAuthFeign.getUserPublicKey(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
            if (resp.getCode() == HttpStatus.OK.value()) {
                ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>)resp;
                this.userAuthConfig.setPubKeyByte(userResponse.getData());
                this.userAuthConfiguration.setPubKeyByte(userResponse.getData());
            }
        }

    }

    @Scheduled(cron = "0 0/10 * * * ?")
    public void refreshServicePubKey() {
        if (serviceAuthConfig.isAuthClientStatus()) {
            BaseResponse resp = serviceAuthFeign.getServicePublicKey(serviceAuthConfig.getClientId(),
                serviceAuthConfig.getClientSecret());
            if (resp.getCode() == HttpStatus.OK.value()) {
                ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>)resp;
                this.serviceAuthConfig.setPubKeyByte(userResponse.getData());
            }
        }

    }

}
