package net.northking.cctp.common.jpa.interceptor;


import net.northking.cctp.common.persistence.rule.CreatedUpdatedRule;
import net.northking.cctp.common.security.authentication.NKSecurityContext;

import java.util.Date;

/**
 * 创建人、创建时间、最近更新人、最近更新时间 拦截器
 *
 * @author xiusong.xie
 * @since 2.4
 */
public class CreatedUpdatedJpaInterceptor extends BasicJpaInterceptor
{
  public static final CreatedUpdatedJpaInterceptor Instance = new CreatedUpdatedJpaInterceptor();

  private CreatedUpdatedJpaInterceptor()
  {
  }

  @Override
  public void beforeInsert(Object entity)
  {
    if (entity instanceof CreatedUpdatedRule)
    {
      CreatedUpdatedRule rule = (CreatedUpdatedRule) entity;
      Date now = new Date();
      rule.setCreatedTime(now);
      rule.setUpdatedTime(now);

      String userId = NKSecurityContext.getUserId();
      rule.setCreatedBy(userId);
      rule.setUpdatedBy(userId);
    }
  }

  @Override
  public void beforeUpdate(Object entity)
  {
    if (entity instanceof CreatedUpdatedRule)
    {
      CreatedUpdatedRule rule = (CreatedUpdatedRule) entity;
      Date now = new Date();
      rule.setUpdatedTime(now);

      String userId = NKSecurityContext.getUserId();
      rule.setUpdatedBy(userId);
    }
  }
}
