package cn.fateverse.query.factory.impl;

import cn.fateverse.common.core.entity.PageInfo;
import cn.fateverse.common.core.utils.TableSupport;
import cn.fateverse.query.entity.DataSourceManage;
import cn.fateverse.query.entity.DynamicPage;
import cn.fateverse.query.mapper.DynamicDataSourceMapper;
import cn.fateverse.query.mapper.dynamic.PostgresDynamicDataSourceMapper;
import com.alibaba.fastjson2.JSONObject;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Clay
 * @date 2023-07-25
 */
public class PostgresDynamicDataSourceFactory extends AbstractDynamicDataSourceFactory {
    @Override
    public SqlSessionFactory getSqlSessionFactory(DataSourceManage dataSource) {
        return super.getSqlSessionFactory(dataSource, "classpath:mapper/dynamic/PostgresDynamicDataSourceMapper.xml");
    }

    @Override
    public DynamicDataSourceMapper getTableMapper(SqlSession sqlSession) {
        return sqlSession.getMapper(PostgresDynamicDataSourceMapper.class);
    }

    @Override
    public String getDataBaseUrl(DataSourceManage dataSourceManage) {
        return "jdbc:postgresql://" + dataSourceManage.getHost() + ":" + dataSourceManage.getPort() + "/" + dataSourceManage.getDbName() + dataSourceManage.getArgs();
    }

    @Override
    public Map<String, Object> getParams(DataSourceManage dataSourceManage) {
        JSONObject param = super.checkParam(dataSourceManage.getParams(), "命名空间不能为空", "namespace");
        Map<String, Object> params = new HashMap<>();
        params.put("namespace", param.getString("namespace"));
        return params;
    }

    @Override
    public DynamicPage getDynamicPage() {
        PageInfo pageInfo = TableSupport.buildPageRequest();
        Integer startNum = pageInfo.getPageSize();
        Integer endNum = (pageInfo.getPageNum() - 1) * pageInfo.getPageSize();
        return DynamicPage.builder()
                .startNum(startNum)
                .endNum(endNum)
                .build();
    }
}
