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.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.stereotype.Component;

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

    private TokenService tokenService = null;

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

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

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     *
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            tokenService = applicationContext.getBean(TokenService.class);
        } catch (Exception ex) {
            Log.error(TokenServiceCall.class, "获取登录服务失败:" + ex.getMessage(), ex);
        }
    }

    /**
     * 请求时初始化token
     */
    public boolean tokenInit() {
        if (tokenService == null) {
            return false;
        }
        if (addHave() == 1) {
            tokenService.tokenInit();
            return true;
        }
        return false;
    }

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

    /**
     * 根据token标记加载
     *
     * @param token  加载标记
     * @return
     */
    @Override
    public TokenData load(String token) {
        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);
    }
}