package com.tofly.codegen.util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.SneakyThrows;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author tuonbed
 * @date 2019/12/18  15:32
 */
public class DataSourceUtil {

    private static  DataSource dataSource;
    private static  JdbcTemplate jdbcTemplate;
    public static String URL;

    public static DataTypeSqlInfo getDataTypeSqlInfo(){
        return DataTypeSqlInfoFactory.getDataTypeSqlInfo(URL);
    }

    @SneakyThrows
    public static  void setDataSource(Map map){
        String url=(String)map.get("url");
        String username=(String)map.get("username");
        String password=(String)map.get("password");
        HikariConfig hikariConfig=new HikariConfig();
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        URL=url;
        hikariConfig.setDriverClassName(DataTypeSqlInfoFactory.getClassname(url));
        if(dataSource!=null){
            ((HikariDataSource) dataSource).close();
        }
        dataSource = new HikariDataSource(hikariConfig);
        if(jdbcTemplate!=null){
            jdbcTemplate=new JdbcTemplate(dataSource);
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    @SneakyThrows
    public  static JdbcTemplate getJdbcTemplate(){
        if(jdbcTemplate!=null){
            return jdbcTemplate;
        }else{
            if(dataSource==null){
                throw new DataSourceLookupFailureException("数据源未获取到");
            }else{
                jdbcTemplate=new JdbcTemplate(dataSource);
                return jdbcTemplate;
            }
        }
    }



}
