package net.northking.cctp.maven.plugin;

import net.northking.cctp.maven.analyse.JDBCConfig;
import net.northking.cctp.maven.analyse.dialects.DBDialects;
import net.northking.cctp.maven.analyse.dialects.Dialect;
import net.northking.cctp.maven.analyse.entity.TableRef;
import net.northking.cctp.maven.analyse.util.DBUtil;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiusong.xie
 * @since 1.0
 */
public abstract class AbsDatabaseLoadMojo extends AbstractMojo
{
  /**
   * jdbcDriver
   */
  @Parameter(required = true)
  protected String jdbcDriver;

  /**
   * jdbcUrl
   */
  @Parameter(required = true)
  protected String jdbcUrl;

  /**
   * jdbcUsername
   */
  @Parameter(required = true)
  protected String jdbcUsername;

  /**
   * jdbcPassword
   */
  @Parameter(required = true)
  protected String jdbcPassword;

  /**
   * database
   */
  @Parameter(required = true)
  protected String database;

  /**
   * schema
   */
  @Parameter(required = true)
  protected String schema;

  /**
   * 包含的表名
   */
  @Parameter(required = false)
  protected String[] tableNames;

  protected List<TableRef> loadTables() throws MojoExecutionException
  {
    getLog().debug("开始加载数据库信息，获取schema=" + schema + ",下的所有表结构数据。");
    initJDBC();
    List<TableRef> tableRefs = new ArrayList<>();
    Dialect dialect = DBDialects.getInstance().getDialect();
    try
    {
      // 获取所有的表
      tableRefs = dialect.getTables(schema, tableNames);
    } catch (Exception e)
    {
      getLog().error(e.getMessage(), e);
      throw new MojoExecutionException("", e);
    } finally
    {
      DBUtil.getInstance().close();
    }
    return tableRefs;
  }

  /**
   * 初始化
   */
  protected void initJDBC()
  {
    JDBCConfig jdbcConfig = JDBCConfig.getInstance();
    jdbcConfig.setDriverClass(jdbcDriver);
    jdbcConfig.setUrl(jdbcUrl);
    jdbcConfig.setCatalog(database);
    jdbcConfig.setUserId(jdbcUsername);
    jdbcConfig.setPassword(jdbcPassword);
  }
}
