package com.leanwo.activiti.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.pool.DruidDataSource;



@Named
public class DatabaseServiceImpl implements DatabaseService {
	private static Logger logger = LoggerFactory.getLogger(DatabaseServiceImpl.class);

    
	@Inject
	private DataSource dataSource;


    @Inject()
    @Named("dataSource0")
    private DruidDataSource dataSource0;
    
	@Override
	@Transactional
	public void schemaUpdate(Long accountId) throws SQLException {
        String url = dataSource0.getUrl().toLowerCase();
        String location = null;
        if(url.contains("sqlserver")) {
            location = "classpath:db/migration/sqlserver";
        }else if(url.contains("mysql")) {
            location = "classpath:db/migration/mysql";
        }else {
            
        }
        
        String baselineVersion = "1.0.0";
        // 判断表是否存在
        boolean isInit = isDbInit();
        if(isInit) {
            baselineVersion = "2.0.0";
        }else {
            baselineVersion = "1.0.0";
        }
        // Create the Flyway instance and point it to the database
        Flyway flyway = Flyway.configure().dataSource(dataSource).locations(location)
            .baselineOnMigrate(true)
            .baselineVersion(baselineVersion)
            .table("flyway_schema_history_workflow_server")
            .load();
            
        // Start the migration
        flyway.migrate();

		logger.debug("数据源:datasource" + accountId + "初始化结束。");
	}

	/**
	 * 获取数据库是否已经初始化完成
	 * @return
	 * @throws SQLException 
	 */
	private boolean isDbInit() throws SQLException {
	    Connection connection = dataSource.getConnection();
	    String sql = "select object_id('ACT_RU_JOB')";
	    Statement statement = connection.createStatement();
	    ResultSet resultSet = statement.executeQuery(sql);
	    boolean isInit = false;
	    if(resultSet.next()) {
	        Object object = resultSet.getObject(1);
	        if(object == null) {
	            isInit = false;
	        }else {
	            isInit = true;
	        }
	    }else {
	        isInit = false;
	    }
	    resultSet.close();
	    statement.close();
	    connection.close();
	    return isInit;
	}
	
}
