package com.yanzuoguang.cloud.service;

import com.yanzuoguang.token.TokenData;
import com.yanzuoguang.token.TokenHelper;
import com.yanzuoguang.token.TokenLoad;
import com.yanzuoguang.util.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Token服务
 *
 * @author 颜佐光
 */
@Component
public class TokenServiceCall implements TokenLoad {

    @Autowired
    private ApplicationContext context;

    private TokenService tokenService = null;

    private int flagCount = 50;

    public TokenServiceCall() {
        TokenHelper.setTokenLoad(this);
    }

    private void init() {
        if (tokenService != null) {
            return;
        }
        if (flagCount < 1) {
            return;
        }
        try {
            tokenService = context.getBean(TokenService.class);
        } catch (Exception ex) {
            Log.error(TokenServiceCall.class, "获取登录服务失败:" + ex.getMessage(), ex);
        } finally {
            flagCount--;
        }
    }

    /**
     * 请求时初始化token
     */
    public void tokenInit() {
        init();
        if (tokenService == null) {
            return;
        }
        tokenService.tokenInit();
    }

    /**
     * 请求时结束token
     */
    public void tokenFinish() {
        init();
        if (tokenService == null) {
            return;
        }
        tokenService.tokenFinish();
    }

    /**
     * 根据token标记加载
     *
     * @param token  加载标记
     * @return
     */
    @Override
    public TokenData load(String token) {
        init();
        if (tokenService == null) {
            return null;
        }
        return tokenService.load(token);
    }
}