package com.eactive.eai.rms.bap.manage.comm.adapter;

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.bap.common.base.BapBaseService;
import com.eactive.eai.rms.bap.manage.comm.property.BapAdapterPropertyDao;
import com.eactive.eai.rms.bap.manage.comm.property.BapPropertyDao;
import com.eactive.eai.rms.common.util.SqlUtil;

@Service("bapAdapterService")
public class BapAdapterService extends BapBaseService {

	@Autowired
	@Qualifier("bapAdapterDao")
	private BapAdapterDao dao;

	@Autowired
	@Qualifier("bapAdapterPropertyDao")
	private BapAdapterPropertyDao adptrPropDao;

	@Autowired
	@Qualifier("bapPropertyDao")
	private BapPropertyDao propDao;

	public HashMap<String, Object> selectList(int startNum,int endNum, String searchAdptrBzwkGroupName, String searchAdptrBzwkGroupDesc) throws Exception {
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		//검색 조건 
		logger.debug("searchAdptrBzwkGroupName===>" + searchAdptrBzwkGroupName + "<====");
		logger.debug("searchAdptrBzwkGroupDesc===>" + searchAdptrBzwkGroupDesc + "<====");

		paramMap.put("searchAdptrBzwkGroupName", searchAdptrBzwkGroupName.toUpperCase());
		paramMap.put("searchAdptrBzwkGroupDesc", searchAdptrBzwkGroupDesc.toUpperCase());
 
		// 전체 목록수 얻기
		int totalCount = dao.selectListCount(paramMap);

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

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

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

		map.put("totalCount", totalCount);

		map.put("list", list);

		return map;
	}	

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

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adptrBzwkGroupName", adptrBzwkGroupName);

		HashMap<String, Object>   detailGroup = dao.adapterGroupDetail(paramMap);
		HashMap<String, Object>   detail      = dao.adapterDetail(paramMap);
		List<Map<String, Object>> list        = dao.propertyList(paramMap);

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

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

		return map;

	}	

	public void insert(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		dao.insertAdapterGroup(paramMap);
		dao.insertAdapter(paramMap);
		adptrPropDao.delete(paramMap);
		adptrPropDao.deleteProperty(paramMap);
		if ( list.length > 0 ) adptrPropDao.insert(paramMap);
		for(HashMap<String, Object> map : list){
			String prptyName = (String)map.get("PRPTYNAME");
			String prpty2Val = (String)map.get("PRPTY2VAL");
			if ( !prptyName.equals("") && !prpty2Val.equals("")){
				HashMap<String, Object> data = new HashMap<String, Object>();
				data.putAll(paramMap);
				data.put("prptyName",prptyName);
				data.put("prpty2Val",prpty2Val);
				adptrPropDao.insertProperty(data);
			}
		}
	}

	public void update(HashMap<String, Object> paramMap, HashMap<String, Object>[] list) throws Exception {
		dao.updateAdapterGroup(paramMap);
		dao.updateAdapter(paramMap);
		adptrPropDao.deleteProperty(paramMap);
		if ( list.length > 0 ) adptrPropDao.update(paramMap);
		for(HashMap<String, Object> map : list){
			String prptyName = (String)map.get("PRPTYNAME");
			String prpty2Val = (String)map.get("PRPTY2VAL");
			if ( !prptyName.equals("") && !prpty2Val.equals("")){
				HashMap<String, Object> data = new HashMap<String, Object>();
				data.putAll(paramMap);
				data.put("prptyName",prptyName);
				data.put("prpty2Val",prpty2Val);
				adptrPropDao.insertProperty(data);
			}
		}
	}	

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

	@SuppressWarnings("unchecked")
	public HashMap<String,String> mkInsertSqlForBapAdptr(HashMap<String, Object> adptrGroup) throws Exception {
		
		StringBuffer adptrGroupInsertSql = new StringBuffer();
		for (String adptrBzwkGroupName : adptrGroup.get("adptrBzwkGroupNameList").toString().split(",")) {
			
			HashMap<String, Object> adptrBzwkGroup = selectDetail(adptrBzwkGroupName);
			HashMap<String, Object>   detail      = (HashMap<String, Object>)adptrBzwkGroup.get("detail");
			List<Map<String, Object>> propList    = (List<Map<String, Object>>)adptrBzwkGroup.get("rows");
			
			// ADAPTER GROUP into BA01
			List<String> columnArr = new ArrayList<String>();
			String[] columnList = {"ADPTRBZWKGROUPNAME","ADPTRCD","ADPTRUSEYN","ADPTRBZWKGROUPDESC"};
			columnArr = Arrays.asList(columnList);
			adptrGroupInsertSql.append("INSERT INTO EAIPKG.TSEAIBA01 (");
			
			// 필드명 입력
			for (String column : columnArr) {
				adptrGroupInsertSql.append((column.equals(columnArr.get(columnArr.size()-1))) ? column : column+",");
			}
			adptrGroupInsertSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnArr) {
				if (column.equals(columnArr.get(columnArr.size()-1))) {
					adptrGroupInsertSql.append("'"+(detail.containsKey(column) ? detail.get(column) : "")+"');\n");
				} else {
					adptrGroupInsertSql.append("'"+(detail.containsKey(column) ? detail.get(column) : "")+"',");
				}
			}
	
			// ADAPTER into BA02
			List<String> columnAdptrArr = new ArrayList<String>();
			String[] columnAdptrList = {"ADPTRBZWKGROUPNAME","ADPTRBZWKNAME","LSTNERCLSNAME","PRPTYGROUPNAME","ADPTRDESC"};
			columnAdptrArr = Arrays.asList(columnAdptrList);
			adptrGroupInsertSql.append("INSERT INTO EAIPKG.TSEAIBA02 (");
			
			// 필드명 입력
			for (String column : columnAdptrArr) {
				adptrGroupInsertSql.append((column.equals(columnAdptrArr.get(columnAdptrArr.size()-1))) ? column : column+",");
			}
			adptrGroupInsertSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnAdptrArr) {
				if (column.equals(columnAdptrArr.get(columnAdptrArr.size()-1))) {
					adptrGroupInsertSql.append("'"+(detail.containsKey(column) ? detail.get(column) : "")+"');\n");
				} else {
					adptrGroupInsertSql.append("'"+(detail.containsKey(column) ? detail.get(column) : "")+"',");
				}
			}
			
			// ADAPTER PROP GROUP into BA03
			List<String> columnPropGrpArr = new ArrayList<String>();
			String[] columnPropGrpList = {"PRPTYGROUPNAME","PRPTYGROUPDESC"};
			columnPropGrpArr = Arrays.asList(columnPropGrpList);
			adptrGroupInsertSql.append("INSERT INTO EAIPKG.TSEAIBA03 (");
			
			// 필드명 입력
			for (String column : columnPropGrpArr) {
				adptrGroupInsertSql.append((column.equals(columnPropGrpArr.get(columnPropGrpArr.size()-1))) ? column : column+",");
			}
			adptrGroupInsertSql.append(") VALUES (");
			// 필드값 입력
			for (String column : columnPropGrpArr) {
				if (column.equals(columnPropGrpArr.get(columnPropGrpArr.size()-1))) {
					adptrGroupInsertSql.append("'"+(detail.containsKey(column) ? detail.get(column) : "")+"');\n");
				} else {
					adptrGroupInsertSql.append("'"+(detail.containsKey(column) ? detail.get(column) : "")+"',");
				}
			}
			
			// ADAPTER PROP LIST into BA04
			for (Map<String, Object> prop : propList) {
				List<String> columnPropArr = new ArrayList<String>();
				String[] columnPropList = {"PRPTYGROUPNAME","PRPTYNAME","PRPTY2VAL"};
				columnPropArr = Arrays.asList(columnPropList);
				adptrGroupInsertSql.append("INSERT INTO EAIPKG.TSEAIBA04 (");
				
				// 필드명 입력
				for (String column : columnPropArr) {
					adptrGroupInsertSql.append((column.equals(columnPropArr.get(columnPropArr.size()-1))) ? column : column+",");
				}
				adptrGroupInsertSql.append(") VALUES (");
				// 필드값 입력
				for (String column : columnPropArr) {
					if (column.equals("PRPTYGROUPNAME")) {
						adptrGroupInsertSql.append("'"+detail.get("PRPTYGROUPNAME")+"',");
					} else if (column.equals(columnPropArr.get(columnPropArr.size()-1))) {
						adptrGroupInsertSql.append("'"+(prop.containsKey(column) ? prop.get(column) : "")+"');\n");
					} else {
						adptrGroupInsertSql.append("'"+(prop.containsKey(column) ? prop.get(column) : "")+"',");
					}
				}
			}
		}

		HashMap<String,String> retMap = new HashMap<String,String>(); 
		if (adptrGroup.get("fileName") != null) {
			OutputStream output = null;
			try {
				String sqlDownloadPath = getProperties("SQL_DOWNLOAD", "DOWNLOAD_PATH");
				String sqlDownloadFile = sqlDownloadPath+adptrGroup.get("fileName");
				output = new FileOutputStream(sqlDownloadFile);
				if (sqlDownloadPath != null) {
					byte[] bt = adptrGroupInsertSql.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 {
			retMap = SqlUtil.executeSql(adptrGroupInsertSql.toString(), "BAP_"+adptrGroup.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 = propDao.getProperties(params);
		
		return props.get("PRPTY2VAL").toString();
	}
}
