package cn.estsh.i3plus.pojo.base.jpa.factory;

import cn.estsh.i3plus.pojo.base.codemaker.SnowflakeIdMaker;
import cn.estsh.i3plus.pojo.base.jpa.daoimpl.BaseRepositoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * @Description : 自定义持久化工厂类
 * @Reference :
 * @Author : alwaysfrin
 * @CreateDate : 2018-09-13 14:55
 * @Modify:
 **/
public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
    public static final Logger LOGGER = LoggerFactory.getLogger(BaseRepositoryFactoryBean.class);

    @Autowired
    public SnowflakeIdMaker snowflakeIdMaker;

    public BaseRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        //LOGGER.info("【初始JPA持久仓】");
        return new BaseRepositoryFactory(em,snowflakeIdMaker);
    }

    //创建一个内部类，该类不用在外部访问
    private static class BaseRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
        private final EntityManager em;
        private final SnowflakeIdMaker snowflakeIdMaker;

        public BaseRepositoryFactory(EntityManager em,SnowflakeIdMaker snowflakeIdMaker) {
            super(em);
            this.em = em;
            this.snowflakeIdMaker = snowflakeIdMaker;
        }

        //设置具体的实现类是BaseRepositoryImpl
        @Override
        protected Object getTargetRepository(RepositoryInformation information) {
            return new BaseRepositoryImpl<T, I>((Class<T>) information.getDomainType(), em,snowflakeIdMaker);
        }

        //设置具体的实现类的class
        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}
