package com.yonge.crud;

import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.yonge.crud.core.Configuration;
import com.yonge.crud.core.CrudSession;
import com.yonge.crud.core.CrudSessionFactory;
import com.yonge.crud.core.GenerateConfiguration;
import com.yonge.crud.core.db.model.Table;

@SpringBootApplication
public class CodegenApplication {

	public static void main(String[] args) throws JAXBException {
		//SpringApplication.run(CodegenApplication.class, args);

		/*
		 * Configuration config = new Configuration("oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@192.168.10.134:1521:orcl", "margin_gy",
		 * "margin_gy", null, "margin_gy");
		 */

		// "src/generateConfigration.xml"
		GenerateConfiguration genConfig = toObject("codegen/src/main/resources/generateConfigration.xml", GenerateConfiguration.class);

		Configuration config = genConfig.getDbConfiguration();

		CrudSessionFactory sessionFactory = config.buildCrudSessionFactory();
		CrudSession session = sessionFactory.openSession();
		List<Table> tables = session.getTables();
		String srcBase = genConfig.getSrcBase();
		String pojoPackageName = genConfig.getPojoPackageName();
		String daoPackageName = genConfig.getDaoPackageName();
		String servicePackageName = genConfig.getServicePackageName();
		String sqlmapPackageName = genConfig.getSqlmapPackageName();
		String sqlmapConfigPackageName = genConfig.getSqlmapConfigPackageName();
		for (Table table : tables) {
			try {
				session.reverse(table, srcBase, pojoPackageName, sqlmapPackageName, daoPackageName, servicePackageName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 生成sqlmapConfig
		session.generateSqlmapConfig(tables, srcBase, sqlmapConfigPackageName, sqlmapPackageName);
		session.closeSession();
	}

	public static <T> T toObject(String systemId, Class<T> clazz) throws JAXBException {
		JAXBContext jc = JAXBContext.newInstance(clazz);
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		StreamSource xml = new StreamSource(systemId);
		JAXBElement<T> je = unmarshaller.unmarshal(xml, clazz);
		return je.getValue();
	}
}
