package com.eactive.eai.rms.bat.manage.rule.adapter;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.bat.common.base.BatBaseService;
import com.eactive.eai.rms.common.util.SqlUtil;
//import com.penta.scpdb.ScpDbAgent;

@Service("batAdapterService")
public class BatAdapterService extends BatBaseService {

	@Autowired
	@Qualifier("batAdapterDao")
	private BatAdapterDao dao;

	public HashMap<String, Object> selectList(int startNum,int endNum, HashMap<String,Object> paramap) throws Exception {
 
		// 전체 목록수 얻기
		int totalCount = dao.selectListCount(paramap);

		paramap.put("startNum" , startNum);// 시작 record
		paramap.put("endNum"   , endNum);// 끝 record

		List<Map<String, Object>> list = dao.selectList(paramap);

		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("totalCount", totalCount);

		map.put("list", list);

		return map;
	}	

	public HashMap<String, Object> selectDetail(String adptrCd) throws Exception {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adptrCd", adptrCd);
		HashMap<String, Object>   detail = dao.adapterDetail(paramMap);
		
		List<Map<String, Object>> listDB = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> listFile = new ArrayList<Map<String, Object>>();

		String adptrKind = detail.get("ADPTRKIND") != null ? (String)detail.get("ADPTRKIND") : "";
		if (adptrKind.equals("1")) {
			listDB = dao.dbAdapterList(paramMap);
			for (int i=0; i<listDB.size(); i++) {
				if (listDB.get(i) != null) {
					String searchDelYn = (String)dao.getDelYnByIntfId(listDB.get(i));
					String intfId = listDB.get(i).get("INTFID") != null ? (String)listDB.get(i).get("INTFID") : "";
					//String delYn = intfId.isEmpty() || searchDelYn == null ? "0" : searchDelYn; 
					String delYn = "";
					if(intfId != null) { //20201027 소스코드 수정
						delYn = intfId.isEmpty() || searchDelYn == null ? "0" : searchDelYn;
					}
					if("0".equals(delYn) ) {
						listDB.get(i).put("DELYN", delYn);
					}
					
				}
			}
		} else {
			listFile = dao.fileAdapterList(paramMap);
			for (int i=0; i<listFile.size(); i++) {
				if (listFile.get(i) != null) {
					String searchDelYn = (String)dao.getDelYnByIntfId(listFile.get(i));
					String intfId = listFile.get(i).get("INTFID") != null ? (String)listFile.get(i).get("INTFID") : "";
				}
			}
		}

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("detail"     , detail);
		map.put("listDB"     , listDB);
		map.put("listFile"   , listFile);

		return map;

	}	

	public void insert(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		dao.insert(paramMap);
	}

	public void update(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		dao.update(paramMap);
	}

	public void delete(HashMap<String, Object> paramMap) throws Exception {
		dao.delete(paramMap);
	}

	public HashMap<String, Object> selectDetailDB(HashMap<String, Object> paramMap) throws Exception {

		Map<String, Object>   detail   = procCLOB(dao.adapterDbDetail(paramMap));
		List<Map<String, Object>> list = dao.layoutList(paramMap);

		// 인터페이스 사용여부에 따른 어댑터 사용여부 설정
		Object searchDelYn = dao.getDelYnByIntfId(detail);
		//String delYn = detail.get("INTFID") == "" || searchDelYn == null ? "0" : (String)searchDelYn; 
		String delYn = "".equals(detail.get("INTFID"))|| searchDelYn == null ? "0" : (String)searchDelYn; //소스코드점검 수정
		if("0".equals(delYn)) {
			detail.put("DELYN", delYn);	
		}
		
		
//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
		//String pvalueDec = agent.ScpDecB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), detail.get("PVALUE").toString());  // DB접속 password 복호화
		
		String pvalueDec = null;
		if(detail.get("PVALUE") != null){ //취약점소스 수정 2020.08.27
//			pvalueDec = agent.ScpDecB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), detail.get("PVALUE").toString());  // FTP접속 password 복호화
		}
		
		detail.replace("PVALUE",pvalueDec);
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("detail" , detail);
		map.put("rows"   , list);

		return map;
	}	

	public void insertDB(HashMap<String, Object> paramMap) throws Exception {

		int adptrCdSeq = dao.getDbAdptrCdSeq( paramMap );
		paramMap.put("adptrCdSeq", adptrCdSeq);
		
		if (paramMap.get("selectUnitCnt") != null) {
			String selCnt = paramMap.get("selectUnitCnt").toString();
			if (selCnt.isEmpty()) paramMap.replace("selectUnitCnt", 0);
		} else {
			paramMap.put("selectUnitCnt", 0);
		}

//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
//		String pvalueEnc = agent.ScpEncB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), paramMap.get("pvalue").toString());  // DB접속 password 암호화
//		paramMap.replace("pvalue",pvalueEnc);
		
		dao.subDbInsert(paramMap);
	}

	public void updateDB(HashMap<String, Object> paramMap,HashMap<String, Object>[] list) throws Exception {

//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
//		String pvalueEnc = agent.ScpEncB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), paramMap.get("pvalue").toString());  // DB접속 password 암호화
//		paramMap.replace("pvalue",pvalueEnc);
	
		dao.subDbUpdate(paramMap);
		
		HashMap<String, Object> data ;
		dao.deleteLayout(paramMap);
		
		int inx = 1;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put( "layoutSeq", inx++ );
			data.put( "colSize",    map.get("COLSIZE") );
			data.put( "colDesc",    map.get("COLDESC") );
			data.put( "colDescEng", map.get("COLDESCENG") );
			data.put( "colType",    map.get("COLTYPE") );
			data.put( "colKind",    map.get("COLKIND") );
			dao.insertLayout(data);
		}
	}	

	public void updateAllDB(HashMap<String, Object> paramMap) throws Exception {
		
//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
//		String pvalueEnc = agent.ScpEncB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), paramMap.get("pvalue").toString());  // DB접속 password 암호화
//		paramMap.replace("pvalue",pvalueEnc);
		
		dao.subDbAllUpdate(paramMap);
	}	

	public void updateDBAdptrSeq(HashMap<String, Object> paramMap) throws Exception {
		
		dao.subDbSeqUpdate(paramMap);
	}
	
	public void deleteDB(HashMap<String, Object> paramMap) throws Exception {
		dao.subDbDelete(paramMap);
		dao.deleteLayout(paramMap);
	}

	public HashMap<String, Object> selectDetailFile(HashMap<String, Object> paramMap) throws Exception {

		Map<String, Object>   detail   = dao.adapterFileDetail(paramMap);
		List<Map<String, Object>> list = dao.layoutList(paramMap);

		// 인터페이스 사용여부에 따른 어댑터 사용여부 설정
		Object searchDelYn = dao.getDelYnByIntfId(detail);
		//String delYn = detail.get("INTFID") == "" || searchDelYn == null ? "0" : (String)searchDelYn; 
		String delYn = "".equals(detail.get("INTFID"))|| searchDelYn == null ? "0" : (String)searchDelYn; //소스코드점검 수정
		detail.put("DELYN", delYn);
		
//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
		//String pvalueDec = agent.ScpDecB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), detail.get("RMTSEVRFTPUSERPWDNAME").toString());  // FTP접속 password 복호화
		String pvalueDec = null;

		if(detail.get("RMTSEVRFTPUSERPWDNAME") != null){ //취약점소스 수정 2020.08.27
//			pvalueDec = agent.ScpDecB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), detail.get("RMTSEVRFTPUSERPWDNAME").toString());  // FTP접속 password 복호화
		}  
		
		detail.replace("RMTSEVRFTPUSERPWDNAME",pvalueDec);

		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("detail" , detail);
		map.put("rows"   , list);

		return map;
	}	

	public void insertFile(HashMap<String, Object> paramMap) throws Exception {

		int adptrCdSeq = dao.getFileAdptrCdSeq( paramMap );
		paramMap.put("adptrCdSeq", adptrCdSeq);
		
//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
//		String pvalueEnc = agent.ScpEncB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), paramMap.get("rmtSevrFTPUserPwdName").toString());  // DB접속 password 암호화
//		paramMap.replace("rmtSevrFTPUserPwdName",pvalueEnc);
		
		dao.subFileInsert(paramMap);
	}

	public void updateFile(HashMap<String, Object> paramMap,HashMap<String, Object>[] list) throws Exception {
		
//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
//		String pvalueEnc = agent.ScpEncB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), paramMap.get("rmtSevrFTPUserPwdName").toString());  // DB접속 password 암호화
//		paramMap.replace("rmtSevrFTPUserPwdName",pvalueEnc);
		
		dao.subFileUpdate(paramMap);
		HashMap<String, Object> data ;
		dao.deleteLayout(paramMap);
		
		int inx = 1;
		for(HashMap<String, Object> map : list){
			data = new HashMap<String, Object>();
			data.putAll(paramMap);
			data.put( "layoutSeq", inx++ );
			data.put( "colSize",    map.get("COLSIZE") );
			data.put( "colDesc",    map.get("COLDESC") );
			data.put( "colDescEng", map.get("COLDESCENG") );
			data.put( "colType",    map.get("COLTYPE") );
			data.put( "colKind",    map.get("COLKIND") );
			dao.insertLayout(data);
		}
	}	

	public void updateAllFile(HashMap<String, Object> paramMap) throws Exception {
		
//		ScpDbAgent agent = new ScpDbAgent(); // DAMO SCP API ScpDbAgent 객체 생성
//		String pvalueEnc = agent.ScpEncB64(getProperties("EXT_MODULE","SCP_PATH"), getProperties("EXT_MODULE","SCP_KEY"), paramMap.get("rmtSevrFTPUserPwdName").toString());  // 서버접속 password 암호화
//		paramMap.replace("rmtSevrFTPUserPwdName",pvalueEnc);
		
		dao.subFileAllUpdate(paramMap);
	}	

	public void updateFileAdptrSeq(HashMap<String, Object> paramMap) throws Exception {
		
		dao.subFileSeqUpdate(paramMap);
	}	

	public HashMap<String, Object> connectionDB(HashMap<String, Object> paramMap) throws Exception {
		
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.transaction.RequestConnectionCommand",paramMap);
		HashMap<String, Object> result = agentUtilService.broadcast(command);
		
		HashMap<String, Object> resultDataMap = new HashMap<String, Object>();
		Iterator<String> iter = result.keySet().iterator();
		String message = iter.next();
		resultDataMap.put("message", (String)result.get(message));
		
		return resultDataMap;
	}	
	
	public HashMap<String, Object> connectionFTP(HashMap<String, Object> paramMap) throws Exception {
		
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.transaction.RequestConnectionCommand",paramMap);
		HashMap<String, Object> result = agentUtilService.broadcast(command);
		
		HashMap<String, Object> resultDataMap = new HashMap<String, Object>();
		Iterator<String> iter = result.keySet().iterator();
		String message = iter.next();
		resultDataMap.put("message", (String)result.get(message));
		
		return resultDataMap;
	}	
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForAdptr(HashMap<String, Object> paramMap) throws Exception {
		
		StringBuffer adptrInserSql = new StringBuffer();

		List<String> adptrCdList = new ArrayList<String>(); 
		if (paramMap.get("adptrCdList") != null) {
			adptrCdList = Arrays.asList(paramMap.get("adptrCdList").toString().split(","));
		}
		for (String adptrCd : adptrCdList) {
			
			HashMap<String, Object> adptrInfo = selectDetail(adptrCd);
			HashMap<String, Object> adptrGroup = new HashMap<String, Object>();
			List<HashMap<String, Object>> adptrList = new ArrayList<HashMap<String,Object>>();

			if (adptrInfo.get("detail") == null) continue;

			adptrGroup = (HashMap<String, Object>)adptrInfo.get("detail");
			String adptrKind = adptrGroup.get("ADPTRKIND") != null ? adptrGroup.get("ADPTRKIND").toString() : "";
			
			if (adptrKind.isEmpty()) continue;
				
			if (adptrKind.equals("1") && adptrInfo.get("listDB") != null) {
				adptrList = (List<HashMap<String, Object>>)adptrInfo.get("listDB");
			} else if (adptrKind.equals("2") && adptrInfo.get("listFile") != null) {
				adptrList = (List<HashMap<String, Object>>)adptrInfo.get("listFile");
			}
			
			// ADAPTER GROUP
			adptrInserSql.append("INSERT INTO EAIPKG.TSEAIEA02 (ADPTRCD,WORKGRPCD,ADPTRBZWKNAME,ADPTRDESC,SNDRCVKIND,ADPTRKIND,JNDIDATASOURCE,LSTNERCLSNAME,PRPTYGROUPID,DELYN) VALUES (");
			adptrInserSql.append("'"+(adptrGroup.containsKey("ADPTRCD") ? adptrGroup.get("ADPTRCD") : "")+"',");
			adptrInserSql.append("'"+(adptrGroup.containsKey("WORKGRPCD") ? adptrGroup.get("WORKGRPCD") : "")+"',");
			adptrInserSql.append("'"+(adptrGroup.containsKey("ADPTRBZWKNAME") ? adptrGroup.get("ADPTRBZWKNAME") : "")+"',");
			adptrInserSql.append("'"+(adptrGroup.containsKey("ADPTRDESC") ? adptrGroup.get("ADPTRDESC") : "")+"',");
			adptrInserSql.append("'"+(adptrGroup.containsKey("SNDRCVKIND") ? adptrGroup.get("SNDRCVKIND") : "")+"',");
			adptrInserSql.append("'"+(adptrGroup.containsKey("ADPTRKIND") ? adptrGroup.get("ADPTRKIND") : "")+"',");
			adptrInserSql.append("'','','',");
			adptrInserSql.append("'"+(adptrGroup.containsKey("DELYN") ? adptrGroup.get("DELYN") : "")+"');\n");
			
			// ADAPTER DETAIL
			for (HashMap<String,Object> adptr : adptrList) {
				adptr.put("adptrCd", adptr.get("ADPTRCD"));
				adptr.put("adptrCdSeq", adptr.get("ADPTRCDSEQ"));
				HashMap<String,Object> adptrMap = new HashMap<String,Object>();
				List<String> columnArr = new ArrayList<String>();

				if (adptrKind.equals("1")) {  // DB 어댑터
					adptrMap = (HashMap<String,Object>)selectDetailDB(adptr).get("detail"); 
					String[] columnList = {"ADPTRCD","ADPTRCDSEQ","SQLNAME","INTFID","SQLNAMEDESC","DBSQL","DBEVENTWHERE","TXCOMMITUNITCNT","SELECTUNITCNT","DELYN",
							"LAYOUTKEY","DIVFIELDORDER","DBMSNAME","DBMSTYPE","DBMSIP","DBMSPORT","IVALUE","PVALUE"};
					columnArr = Arrays.asList(columnList);
					adptrInserSql.append("INSERT INTO EAIPKG.TSEAIEA03 (");
				} else { // FILE 어댑터
					adptrMap = (HashMap<String,Object>)selectDetailFile(adptr).get("detail"); 
					String[] columnList = {"ADPTRCD","ADPTRCDSEQ","INTFID","FTPNAME","FTPNAMEDESC","FTPHOSTNAME","RMTSEVRFTPPORTNONAME","RMTSEVRFTPUID",
							"RMTSEVRFTPUSERPWDNAME","FTPARCHIVEDIR","FTPSTOREFILEPATTERN","NEXTOPTION","CHECKNAME","FTPCHECKDIR","SYSTEMNAME",
							"SYSTEMOWNER","SYSTEMOWNERTELEPHONE","SYSTEMOTHERTXT","SECTIONVAL","FTPBACKUPDIR","FTPTYPE","LAYOUTKEY"};
					columnArr = Arrays.asList(columnList);
					adptrInserSql.append("INSERT INTO EAIPKG.TSEAIEA05 (");
				}
				
				// 필드명 입력
				for (String column : columnArr) {
					adptrInserSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
				}
				adptrInserSql.append(") VALUES (");
				// 필드값 입력
				String[] columnInt = {"ADPTRCDSEQ","TXCOMMITUNITCNT","SELECTUNITCNT","DIVFIELDORDER"};  // Integer 컬럼 구분
				for (String column : columnArr) {
					if (!paramMap.containsKey("fileName") && "PVALUE".equals(column)) adptrMap.replace(column,"");  // SCP 암복호화 KEY가 다를 수 있어 빈값으로 복제
					if (column.equals("DBSQL")) {
						adptrMap.replace(column,adptrMap.get(column).toString().replace("'","''"));  // 쿼리 내 Single Quote (')->('')변경
					}
					if (column.equals(columnArr.get(columnArr.size()-1))) {
						if (Arrays.asList(columnInt).contains(column)) {
							adptrInserSql.append((adptrMap.containsKey(column) ? adptrMap.get(column) : 0)+");\n");
						} else {
							adptrInserSql.append("'"+(adptrMap.containsKey(column) ? adptrMap.get(column) : "")+"');\n");
						}
					} else {
						if (Arrays.asList(columnInt).contains(column)) {
							adptrInserSql.append((adptrMap.containsKey(column) ? adptrMap.get(column) : 0)+",");
						} else {
							adptrInserSql.append("'"+(adptrMap.containsKey(column) ? adptrMap.get(column) : "")+"',");
						}
					}
				}
				
				// ADAPTER LAYOUT
				if (adptrMap.get("LAYOUTKEY") != null && adptrMap.get("LAYOUTKEY").toString().equals("1")) {  // Layout 사용시
					List<Map<String, Object>> adptrLayoutList = new ArrayList<Map<String, Object>>();
					if (adptrKind.equals("1")) {  // DB 어댑터
						adptrLayoutList = (List<Map<String, Object>>)selectDetailDB(adptr).get("rows"); 
					} else { // FILE 어댑터
						adptrLayoutList = (List<Map<String, Object>>)selectDetailFile(adptr).get("rows"); 
					}
					String[] layoutColumnList = {"ADPTRCD","ADPTRCDSEQ","LAYOUTSEQ","INTFID","ORDERSEQ","COLSIZE","COLDEPTH","COLDESC","COLTYPE","COLDESCENG","COLKIND"};
					List<String> layoutColumnArr = Arrays.asList(layoutColumnList);
					
					for (Map<String, Object> adptrLayout : adptrLayoutList ) {
						adptrInserSql.append("INSERT INTO EAIPKG.TSEAIES06 (");
						// Layout 필드명 입력
						for (String column : layoutColumnArr) {
							adptrInserSql.append((column.equals(layoutColumnArr.get(layoutColumnArr.size()-1))) ? column : column+",");
						}
						adptrInserSql.append(") VALUES (");
						// 필드값 입력
						String[] layoutColumnInt = {"ADPTRCDSEQ","LAYOUTSEQ","ORDERSEQ","COLDEPTH"};  // Integer 컬럼 구분
						for (String column : layoutColumnArr) {
							if (column.equals(layoutColumnArr.get(layoutColumnArr.size()-1))) {
								if (Arrays.asList(layoutColumnInt).contains(column)) {
									adptrInserSql.append((adptrLayout.containsKey(column) ? adptrLayout.get(column) : 0)+");\n");
								} else {
									adptrInserSql.append("'"+(adptrLayout.containsKey(column) ? adptrLayout.get(column) : "")+"');\n");
								}
							} else {
								if (Arrays.asList(layoutColumnInt).contains(column)) {
									adptrInserSql.append((adptrLayout.containsKey(column) ? adptrLayout.get(column) : 0)+",");
								} else {
									adptrInserSql.append("'"+(adptrLayout.containsKey(column) ? adptrLayout.get(column) : "")+"',");
								}
							}
						}						
					}
				}
			}
		}
		
		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (paramMap.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath+paramMap.get("fileName").toString();
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = adptrInserSql.toString().getBytes();
					output.write(bt);
					output.close();
				}
				retMap.put("path", sqlDownloadPath);
			} catch (Exception e) {
				logger.error( e.getMessage(), e);
			} finally {
				if(output != null) try { output.close(); } catch(Exception ee) {logger.error( ee.getMessage(), ee);}
			}
		} else if (paramMap.get("svrType") != null){
			retMap = SqlUtil.executeSql(adptrInserSql.toString(), "ISG_"+paramMap.get("svrType").toString().toUpperCase());
		}
		
		return retMap;
	}
	
	public void deleteFile(HashMap<String, Object> paramMap) throws Exception {
		dao.subFileDelete(paramMap);
		dao.deleteLayout(paramMap);
	}

	private Map<String, Object> procCLOB( Map<String, Object> map ){

		Object obj = map.get("DBSQL");
		
		if(obj instanceof Clob){
			Clob clob = (Clob)obj;
			StringBuffer output = null;
			Reader       input = null;
			char[]       buffer = null;
			int          byteRead=0;
			try {
	            output=new StringBuffer();
	            input=clob.getCharacterStream();
	            buffer = new char[1024];
	            byteRead=0;                
	            while((byteRead=input.read(buffer,0,1024))!=-1){
	            	output.append(buffer,0,byteRead);
	            }
	            map.put("DBSQL",output.toString());
			} catch (Exception e) {
				map.put("DBSQL","");
				logger.error( e.getMessage(), e);
			} finally {
				if ( input != null )
					try {
						input.close();						
					} catch (Exception e2) {
						logger.error( e2.getMessage(), e2);
					}
			}
		}else{
			
		}
		return map;
	}
	
	private String getProperties(String propGroup, String propName) throws Exception {
		HashMap<String,Object> params = new HashMap<String,Object>();
		params.put("prptyGroupName", propGroup);
		params.put("prptyName", propName);
		
		HashMap<String, Object> props = dao.getProperties(params);
		
		return props.get("PRPTYDETAIL").toString();
	}

	public String generateAdapterCode(String paramAdapterCode) throws Exception {
		
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("adapterCode", paramAdapterCode);
		List<Map<String, Object>> adapterList = dao.selectAdapterList(paramMap);
		
		if(adapterList == null || adapterList.size() == 0) {
			return paramAdapterCode+"01";
		} else {
			int max = 
					adapterList.stream()
						.filter(adapter -> adapter.get("ADPTRCD") != null)
						.map(adapter -> adapter.get("ADPTRCD").toString())
						.mapToInt(adapter -> Integer.parseInt(adapter.substring(adapter.length()-2, adapter.length())))
						.max().orElse(1);
			
			if(max < 10) {
				max += 1;
				return paramAdapterCode + "0" + max; 
			} else if(max < 99) {
				max += 1;
				return paramAdapterCode + max;
			} else {
				throw new Exception("더 이상 어댑터를 만들 수 없습니다.");
			}
		}
		
	}
}
