package cn.axzo.msg.center.notices.common.domain;

import cn.axzo.msg.center.notices.common.enums.ReturnCodeEnum;
import cn.axzo.msg.center.notices.common.exception.BizException;
import cn.azxo.framework.common.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务上下文本地变量
 *
 * @author zhaoyong
 * @see ServiceContextHolder
 * @since 2021-08-19 19:47
 */
@Slf4j
public class ServiceContextHolder {

  private static ThreadLocal<ServiceContext> tl = new ThreadLocal<>();

  public static ServiceContext get() {
    if (tl.get() == null) {
      LogUtil.error("service context not exist");
      throw new BizException(ReturnCodeEnum.SYSTEM_ERROR);
    }
    return tl.get();
  }

  public static void set(ServiceContext sc) {
    if (tl.get() != null) {
      LogUtil.error("service context not null");
      tl.remove();
    }
    tl.set(sc);
  }

  public static void cleanUp() {
    try {
      if (tl.get() != null) {
        tl.remove();
      }
    } catch (Exception e) {
      LogUtil.error(e.getMessage(), e);
    }
  }

}
