package cn.iocoder.foodnexus.module.customerpermission.core.aop;

import cn.iocoder.foodnexus.module.customerpermission.core.annotation.CustomerVisible;
import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.LinkedList;
import java.util.List;

/**
 * {@link CustomerVisible} 注解的 Context 上下文
 *
 * @author 芋道源码
 */
public class CustomerPermissionContextHolder {

    /**
     * 使用 List 的原因，可能存在方法的嵌套调用
     */
    private static final ThreadLocal<LinkedList<CustomerVisible>> DATA_PERMISSIONS =
            TransmittableThreadLocal.withInitial(LinkedList::new);

    /**
     * 获得当前的 CustomerVisible 注解
     *
     * @return CustomerVisible 注解
     */
    public static CustomerVisible get() {
        return DATA_PERMISSIONS.get().peekLast();
    }

    /**
     * 入栈 CustomerVisible 注解
     *
     * @param CustomerVisible CustomerVisible 注解
     */
    public static void add(CustomerVisible CustomerVisible) {
        DATA_PERMISSIONS.get().addLast(CustomerVisible);
    }

    /**
     * 出栈 CustomerVisible 注解
     *
     * @return CustomerVisible 注解
     */
    public static CustomerVisible remove() {
        CustomerVisible CustomerVisible = DATA_PERMISSIONS.get().removeLast();
        // 无元素时，清空 ThreadLocal
        if (DATA_PERMISSIONS.get().isEmpty()) {
            DATA_PERMISSIONS.remove();
        }
        return CustomerVisible;
    }

    /**
     * 获得所有 CustomerVisible
     *
     * @return CustomerVisible 队列
     */
    public static List<CustomerVisible> getAll() {
        return DATA_PERMISSIONS.get();
    }

    /**
     * 清空上下文
     *
     * 目前仅仅用于单测
     */
    public static void clear() {
        DATA_PERMISSIONS.remove();
    }

}
