package com.sf.apijson.config;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper;

@Order(value = 10)
@Component
public class ApijsonDataSource implements ApplicationRunner {
	@Resource(name = "masterDataSource")
	private DataSource dataSource;
	
	// value: 数据源相关信息
	private static Map<String, ApijsonDataSourceConfig> dataSourceMap = new HashMap<>();
	@Override
	public void run(ApplicationArguments args) throws Exception {
		initJdbcDataSource(); // 初始化spring application.xml 数据库连接池
		//initJdbcDataSourceDefault();
	}
	
	/***
	 * 获取数据源详细信息
	 * 
	 * @return
	 */
	public static ApijsonDataSourceConfig getDefaultDetail() {
		// 不存在交给框架处理
		return dataSourceMap.get(null);
	}
	
	 /**
     * 根据url获取库名
     * @param url
     * @return
     */
    public static String getLibname(String url) {
        Pattern p = Pattern.compile("jdbc:(?<db>\\w+):.*((//)|@)(?<host>.+):(?<port>\\d+)(/|(;DatabaseName=)|:)(?<dbName>\\w+)\\??.*");
        Matcher m = p.matcher(url);
        if(m.find()) {
            return m.group("dbName");
        }
        return null;
    }
    
    
    private void initJdbcDataSourceDefault() {
    	DruidDataSourceWrapper wrapper = (DruidDataSourceWrapper)dataSource;
    	String schema = getLibname(wrapper.getRawJdbcUrl());
    	ApijsonDataSourceConfig config = new ApijsonDataSourceConfig();
		config.setSchema(schema);
		dataSourceMap.put(null, config);
    }
    
	/***
	 * 初始化数据库连接池
	 */
	private void initJdbcDataSource() {
		DruidDataSourceWrapper wrapper = (DruidDataSourceWrapper)dataSource;
		String[] arrayUrl = wrapper.getRawJdbcUrl().split("/");
		arrayUrl = arrayUrl[arrayUrl.length-1].split("[?]");
		String schema = arrayUrl[0]; // 数据库名;
		ApijsonDataSourceConfig config = new ApijsonDataSourceConfig();
		config.setSchema(schema);
		dataSourceMap.put(null, config);
	}

}
