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

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
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.rms.bat.common.base.BatBaseService;
import com.eactive.eai.rms.bat.manage.rule.adapter.BatAdapterDao;
import com.eactive.eai.rms.common.util.SqlUtil;

@Service("batInterfaceService")
public class BatInterfaceService extends BatBaseService {

	@Autowired
	@Qualifier("batInterfaceDao")
	private BatInterfaceDao dao;

	@Autowired
	@Qualifier("batAdapterDao")
	private BatAdapterDao adaptdao;
	
	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 intfId) throws Exception {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("intfId", intfId);
		paramMap.put("sndRcvKindO", "2");

		HashMap<String, Object>   detail   = dao.selectDetail(paramMap);
		List<Map<String, Object>> listDB   = dao.dbAdapterList(paramMap);
		List<Map<String, Object>> listFile = dao.fileAdapterList(paramMap);
		
		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) throws Exception {
		dao.insert(paramMap);
	}

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

	public void updateSndAdpt(HashMap<String, Object> paramMap) throws Exception {
		
		if (paramMap.get("batchType").toString().startsWith("D")) {
			dao.sndAdptDbUpdate(paramMap);
		} else {
			dao.sndAdptFileUpdate(paramMap);
		}		
	}		
	
	public void updateRcvAdpt(HashMap<String, Object> paramMap) throws Exception {
		
		if (paramMap.get("batchType") != null && paramMap.get("batchType").toString().endsWith("D")) {
			dao.rcvAdptDbUpdate(paramMap);
		} else {
			if (paramMap.get("adptrKind") != null && paramMap.get("adptrKind").toString().equals("1")) {
				dao.rcvAdptDbUpdate(paramMap);  // DF 수신 후 송신DB 업데이트 쿼리 등록
			} else {
				dao.rcvAdptFileUpdate(paramMap);
			}
		}		
	}	

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

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

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

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

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

		map.put("totalCount", totalCount);

		map.put("list", list);

		return map;

	}
	
	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInserSqlForIntf(HashMap<String, Object> paramMap) throws Exception {
		
		StringBuffer intfInserSql = new StringBuffer();

		List<String> intfIdList = new ArrayList<String>(); 
		if (paramMap.get("intfIdList") != null) {
			intfIdList = Arrays.asList(paramMap.get("intfIdList").toString().split(","));
		}
		for (String intfId : intfIdList) {
			HashMap<String, Object> intfInfo = (HashMap<String, Object>)selectDetail(intfId).get("detail");

			// ADAPTER GROUP
			String[] columnList = {"INTFID","INTFNAME","INTFDESC","WORKGRPCD","SNDADPTRCD","SNDADPTRCDSEQ","BATCHTYPE","REGDATE","REGUSERID",
								   "MODDATE","MODUSERID","INTFSTARTDATE","INTFENDDATE","DELYN","EVENTCALLVAL","POSTJOBHOSTNAME","POSTJOBPORTNONAME",
								   "POSTJOBUID","POSTJOBUSERPWDNAME","POSTJOBCMD","LEVEL4"};
			List<String> columnArr = Arrays.asList(columnList);
			intfInserSql.append("INSERT INTO EAIPKG.TSEAIEA04 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				intfInserSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			intfInserSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					intfInserSql.append("'"+(intfInfo.containsKey(column) ? intfInfo.get(column) : "")+"');\n");
				} else {
					intfInserSql.append("'"+(intfInfo.containsKey(column) ? intfInfo.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 = intfInserSql.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(intfInserSql.toString(), "ISG_"+paramMap.get("svrType").toString().toUpperCase());
		}
		
		return retMap;
	}
	
	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 = adaptdao.getProperties(params);
		
		return props.get("PRPTYDETAIL").toString();
	}
}
