package cn.hmsoft.jdbc.core;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import cn.hmsoft.jdbc.entity.ColumnEntity;
import cn.hmsoft.jdbc.entity.DataRecord;
import cn.hmsoft.jdbc.entity.DatabaseType;
import cn.hmsoft.jdbc.entity.TableEntity;
import cn.hmsoft.jdbc.exception.ExecuteSqlException;

/*******************
 * 数据库基本信息 通用数据库操作
 * 
 * @author zxq
 * @create 2019-05-06 23:25:32
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
@Repository
public class DatabaseDao extends PlatformDaoSupport<DataRecord> {
	/******
	 * 获取当前用户能访问的所有表,s01表名,s02表的描述信息
	 */
	public List<TableEntity> getTables() {
		String sql = "";
		// 找出当前连接的数据库
		try {
			String databaseName = this.getDatabaseName();
			sql = this.getSqlGenerator().queryTables(databaseName);
			return this.listBySql(TableEntity.class, sql);
		} catch (Exception e) {
			throw new ExecuteSqlException(sql, e);
		}
	}

	/******
	 * 获取当前用户能访问的所有表,s01表名,s02表的描述信息
	 */
	public List<ColumnEntity> getColumns(String tableName) {
		String sql = "";
		// 找出当前连接的数据库
		String databaseName = this.getDatabaseName();
		sql = this.getSqlGenerator().queryColumns(databaseName, tableName);
		try {
			if (JdbcProperty.DATABAETYPE == DatabaseType.Sqlite) {
				// sqllit单独处理
				List<ColumnEntity> array = new ArrayList<ColumnEntity>();
				for(Map<String,Object> map : this.listMapBySql(sql)) {
					ColumnEntity col = new ColumnEntity();
					col.setColumn_name(map.get("name").toString());
					col.setColumn_type(map.get("type").toString());
					array.add(col);
				}
				return array;
			} else {
				return this.listBySql(ColumnEntity.class, sql, tableName);
			}
		} catch (Exception e) {
			throw new ExecuteSqlException(sql, e);
		}
	}

	/****
	 * 获取数据库当前时间
	 */
	public LocalDateTime getCurrentTime() {
		String sql = this.getSqlGenerator().queryCurrentTime();
		try {
			DataRecord dr = this.findBySql(sql);
			return dr.getLdt01();
		} catch (Exception e) {
			throw new ExecuteSqlException(sql, e);
		}
	}

	public String getDatabaseName() {
		try {
			return this.getJdbcTemplate().getDataSource().getConnection().getCatalog();
		} catch (Exception e) {
			throw new ExecuteSqlException(e.getMessage());
		}
	}
}
