package cn.fateverse.query.factory;

import cn.fateverse.common.core.exception.CustomException;
import cn.fateverse.query.entity.DataSourceManage;
import cn.fateverse.query.enums.DynamicSourceEnum;
import cn.fateverse.query.mapper.DynamicDataSourceMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Clay
 * @date 2023-07-16
 */
@Component
public class DynamicDataSourceService {

    private final Map<Long, SqlSessionFactory> factoryMap = new ConcurrentHashMap<>(8);

    private static final ThreadLocal<SqlSession> session = new ThreadLocal<>();


    /**
     * 获取到数据源的SqlSession
     *
     * @param dataSourceManage 数据源
     * @return 返回DynamicDataSourceMapper对象
     */
    public DynamicDataSourceMapper getMapper(DataSourceManage dataSourceManage) {
        SqlSessionFactory sqlSessionFactory = factoryMap.get(dataSourceManage.getId());
        DynamicSourceEnum type = dataSourceManage.getType();
        if (sqlSessionFactory == null) {
            synchronized (this) {
                sqlSessionFactory = factoryMap.get(dataSourceManage.getId());
                if (null == sqlSessionFactory) {
                    sqlSessionFactory = type.getDynamicDataSourceFactory().getSqlSessionFactory(dataSourceManage);
                    factoryMap.put(dataSourceManage.getId(), sqlSessionFactory);
                }
            }
        }
        SqlSession sqlSession = sqlSessionFactory.openSession();
        session.set(sqlSession);
        return type.getDynamicDataSourceFactory().getTableMapper(sqlSession);
    }


    /**
     * 检查当前数据源是否可连接
     *
     * @param dataSourceManage 数据源管理对象
     * @return 如果数据源可连接则返回true，否则返回false
     */
    public Boolean checkDataSource(DataSourceManage dataSourceManage) {
        try {
            SqlSessionFactory sqlSessionFactory = dataSourceManage.getType().getDynamicDataSourceFactory().getSqlSessionFactory(dataSourceManage);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            DynamicDataSourceMapper tableMapper = dataSourceManage.getType().getDynamicDataSourceFactory().getTableMapper(sqlSession);
            tableMapper.checkSource();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof CustomException) {
                throw e;
            }
            return Boolean.FALSE;
        }
    }

    /**
     * 删除Session工厂缓存
     *
     * @param dataSourceId 数据源id
     */
    public synchronized void remove(Long dataSourceId) {
        factoryMap.remove(dataSourceId);
    }

    /**
     * 关闭sqlSession
     */
    public void closeSqlSession() {
        SqlSession sqlSession = session.get();
        if (sqlSession != null) {
            sqlSession.close();
            session.remove();
        }
    }

}
