package com.yanzuoguang.cloud.service;

import com.yanzuoguang.token.TokenData;
import com.yanzuoguang.token.TokenHelper;
import com.yanzuoguang.token.TokenLoad;
import com.yanzuoguang.util.cache.MemoryCache;
import com.yanzuoguang.util.helper.StringHelper;
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 = 1;

    private MemoryCache<Integer> countCache = new MemoryCache<>();

    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 boolean tokenInit() {
        init();
        if (tokenService == null) {
            return false;
        }
        if (addHave() == 1) {
            tokenService.tokenInit();
            return true;
        }
        return false;
    }

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

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

    private int addHave(int flag) {
        String id = StringHelper.toString(Thread.currentThread().getId());
        int from = StringHelper.toInt(countCache.get(id));
        int to = from + flag;
        countCache.put(id, to);
        if (to == 0) {
            countCache.remove(id);
        }
        return to;
    }

    private int addHave() {
        return addHave(1);
    }

    private int subHave() {
        return addHave(-1);
    }
}