package com.eactive.eai.batch.osd;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;

public class OutsideDAO extends BaseDAO implements OutsideQuery
{
    /**
     * TSEAIBJ06을 뒤져서 모든 대외기관 정보를 읽어서 HashMap으로 리턴한다.
     */
    public HashMap<String, ArrayList<OutsideVO>> getAllOutsideInfo() throws DAOException
    {
        HashMap<String, ArrayList<OutsideVO>> all = new HashMap<String, ArrayList<OutsideVO>>();
        ResultSet rs = null;
        ArrayList<OutsideVO>   al = null;
        OutsideVO vo = null;
        try
        {
            this.connect(GET_ALL_OUTSIDE);
//            logger.debug(">> 대외기관 정보......\n" + GET_ALL_OUTSIDE);
            rs = this.executeQuery();
            
            while(rs.next())
            {
                vo = new OutsideVO();

                vo.setBatchCode   (rs.getString("BjobBzwkDstcd"       ).trim());
                vo.setOsdCode     (rs.getString("OsidInstiDstcd"      ).trim());
                vo.setOsdName     (rs.getString("OsidInstiName"       ).trim());
                vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName"  ).trim());
                vo.setSendRuleCode(rs.getString("SendPrcssRuleCd"     ).trim());
                vo.setRecvRuleCode(rs.getString("RecvPrcssRuleCd"     ).trim());
                vo.setOsdSendPrpt (rs.getString("EAIFileSendPtrnDstcd").trim());
                vo.setOsdRecvPrpt (rs.getString("EAIFileRecvPtrnDstcd").trim());
                vo.setBlkSize     (rs.getInt   ("TelgmBlckSize"       ));
                vo.setSequenceSize(rs.getInt   ("TelgmSernoSize"      ));
                vo.setBizStartIdx (rs.getInt   ("TranStartIndx"       ));
                vo.setBizEndIdx   (rs.getInt   ("TranEndIndx"         ));
                vo.setPacketSize  (rs.getInt   ("TelgmPcketSize"      ));
                vo.setBatchName   (rs.getString("BjobBzwkName"        ).trim());
                
//                logger.debug("  - ["+ vo.getBatchCode() +"] ["+ vo.getBatchName() +"] ["+ vo.getOsdCode() +"] ["+ vo.getOsdName() +"] ["+ vo.getSendRuleCode() +"] ["+ vo.getRecvRuleCode() +"]");
                al =  all.remove(vo.getBatchCode());
                if (al == null) {
                    al = new ArrayList<OutsideVO>();
                }
                al.add(vo);
                all.put(vo.getBatchCode(), al);
            }
        } catch(Exception e) {
            throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS001"));
        } finally {
            this.disconnect();
        }
        return all;
    }

    /**
     * TSEAIBJ05를 읽어서 모든 대외기관 링크정보를 읽어서 HashMap으로 리턴한다.
     * 각 대외기관에 대해 2개이상의 링크정보가 있을수 있다.
     * HashMap에는 대외기관 코드로 ArrayList를 넣고,
     * 각 ArrayList에는 개발 대외기관 링크정보(OutsideLinkVO)인스탄스가 들어간다.
     */
    public HashMap<String, ArrayList<OutsideLinkVO>> getAllOutsideLinkInfo() throws DAOException
    {
        HashMap<String, ArrayList<OutsideLinkVO>> all = new HashMap<String, ArrayList<OutsideLinkVO>>();
        ResultSet rs = null;
        ArrayList<OutsideLinkVO>   al = null;
        OutsideLinkVO vo = null;
        try
        {
            this.connect(GET_ALL_LINKINFO);
            rs = this.executeQuery();

            logger.debug(">> 대외기관별 연결 정보......");
            while(rs.next())
            {
                vo = new OutsideLinkVO();

                vo.setSyslinkCode (rs.getString("SysLnkgDstcd"      ).trim());
                vo.setBatchCode   (rs.getString("BjobBzwkDstcd"     ).trim());
                vo.setOsdCode     (rs.getString("OsidInstiDstcd"    ).trim());
                vo.setReqResCode  (rs.getString("RqstRspnsDstcd"    ).trim());
                vo.setLinkIP      (rs.getString("LnkgIPInfoName"    ).trim());
                vo.setLinkPort    (rs.getString("LnkgPortInfoName"  ).trim());
                vo.setUserID      (rs.getString("LnkgID"            ).trim());
                vo.setPwd         (rs.getString("LnkgPwd"           ).trim());
                vo.setToVal       (rs.getInt   ("ToutVal"           ));
                vo.setLinkStatus  (rs.getString("TCirtLnkgStusCd"   ).trim());
                vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName").trim());
                vo.setAdpName     (rs.getString("AdptrBzwkName"     ).trim());

                logger.debug("  - ["+ vo.getBatchCode() +"] ["+ vo.getOsdCode() +"] ["+ vo.getReqResCode() +"] ["+ vo.getLinkPort() +"] ["+ vo.getLinkIP() +"]");
                al = all.remove(vo.getOsdCode());
                if (al == null) {
                    al = new ArrayList<OutsideLinkVO>();
                }
                al.add(vo);
                all.put(vo.getOsdCode(), al);
            }
        } catch(Exception e) {
            throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS002"));
        } finally {
            this.disconnect();
        }
        return all;
    }
    
	public int updateOutsideLinkInfo(OutsideLinkVO vo) throws DAOException {

		int       retValue = 0;
		int       index    = 0;

		try {

			this.connect(UPDATE_LINKINFO_ID_PASSWORD);

			index = 1;
			this.preparedStatement.setString(index++, vo.getUserID()      );
			this.preparedStatement.setString(index++, vo.getPwd()         );
			this.preparedStatement.setString(index++, vo.getSyslinkCode() );

			retValue = this.executeUpdate();

			if (retValue == 0) {
				String errMsg = "";//ExceptionUtil.getErrorCode("BECEAICLG012", new String[] {uuid, subUuid});  //배치로그 Master 테이블 종료 update 건수가 0 건입니다.(UUID: ?, subUUID: ?)
				throw new DAOException(errMsg);
			}

		} catch (DAOException ex) {
			throw ex;
		} catch (Exception ex) {
			String errMsg = "";//ExceptionUtil.getErrorCode(ex, "BECEAICLG013", new String[] {uuid, subUuid});  //배치로그 Master 테이블 종료 update 시 오류가 발생하였습니다.(UUID: ?, subUUID: ?)
			throw new DAOException(errMsg);
		} finally {
			disconnect();
		}
		return retValue;
	}
	
    /**
     * TSEAIBJ06을 KEY로 검색하여 해당 대외기관 정보를 읽어서 OutsideVO을 리턴한다.
     */
    public OutsideVO getOutsideInfoByKey( String bjobBzwkDstcd, String osidInstiDstcd) throws DAOException
    {
        ResultSet rs = null;
        OutsideVO vo = null;
		int index = 0;

		try
        {
            this.connect(GET_OUTSIDE_BY_KEY);
//			logger.debug("OutsideDAO.getOutsideInfoByKey() >>> 수행 SQL 문 : \n"+ GET_OUTSIDE_BY_KEY);

			index = 1;
			this.preparedStatement.setString(index++, bjobBzwkDstcd);	
//			logger.debug("OutsideDAO.getOutsideInfoByKey() >>> 바인드("+(index-1)+") : ["+ bjobBzwkDstcd +"]");
			this.preparedStatement.setString(index++, osidInstiDstcd.trim()  );	
//			logger.debug("OutsideDAO.getOutsideInfoByKey() >>> 바인드("+(index-1)+") : ["+ osidInstiDstcd.trim() +"]");

            rs = this.executeQuery();

            if (rs.next()){
                vo = new OutsideVO();

                vo.setBatchCode   (rs.getString("BjobBzwkDstcd"       ).trim());
                vo.setOsdCode     (rs.getString("OsidInstiDstcd"      ).trim());
                vo.setOsdName     (rs.getString("OsidInstiName"       ).trim());
                vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName"  ).trim());
                vo.setSendRuleCode(rs.getString("SendPrcssRuleCd"     ).trim());
                vo.setRecvRuleCode(rs.getString("RecvPrcssRuleCd"     ).trim());
                vo.setOsdSendPrpt (rs.getString("EAIFileSendPtrnDstcd").trim());
                vo.setOsdRecvPrpt (rs.getString("EAIFileRecvPtrnDstcd").trim());
                vo.setBlkSize     (rs.getInt   ("TelgmBlckSize"       ));
                vo.setSequenceSize(rs.getInt   ("TelgmSernoSize"      ));
                vo.setBizStartIdx (rs.getInt   ("TranStartIndx"       ));
                vo.setBizEndIdx   (rs.getInt   ("TranEndIndx"         ));
                vo.setPacketSize  (rs.getInt   ("TelgmPcketSize"      ));
                vo.setBatchName   (rs.getString("BjobBzwkName"        ).trim());

//                logger.debug("  - ["+ vo.getBatchCode() +"] ["+ vo.getBatchName() +"] ["+ vo.getOsdCode() +"] ["+ vo.getOsdName() +"] ["+ vo.getSendRuleCode() +"] ["+ vo.getRecvRuleCode() +"]");
            }
        } catch(Exception e) {
            throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS001"));
        } finally {
            this.disconnect();
        }
        return vo;
    }
    
    /**
     * TSEAIBJ05를 읽어서 모든 특정 대외 기관 링크정보를 읽어서 HashMap으로 리턴한다.
     * 각 대외기관에 대해 2개이상의 링크정보가 있을수 있다.
     * HashMap에는 대외기관 코드로 ArrayList를 넣고,
     * 각 ArrayList에는 개발 대외기관 링크정보(OutsideLinkVO)인스탄스가 들어간다.
     */
    public ArrayList<OutsideLinkVO> getOutsideLinkInfoByOsdCode(String bjobBzwkDstcd, String osidInstiDstcd) throws DAOException
    {
        ResultSet rs = null;
        ArrayList<OutsideLinkVO>   al = new ArrayList<OutsideLinkVO>();
        OutsideLinkVO vo = null;
        int index = 0;
        try
        {
            this.connect(GET_ALL_LINKINFO_BY_OUTSIDE_KEY);
//			logger.debug("OutsideDAO.getOutsideLinkInfoByOsdCode() >>> 수행 SQL 문 : \n"+ GET_ALL_LINKINFO_BY_OUTSIDE_KEY);


            index = 1;
			this.preparedStatement.setString(index++, bjobBzwkDstcd);	
//			logger.debug("OutsideDAO.getOutsideLinkInfoByOsdCode() >>> 바인드("+(index-1)+") : ["+ bjobBzwkDstcd +"]");
			this.preparedStatement.setString(index++, osidInstiDstcd.trim()  );	
//			logger.debug("OutsideDAO.getOutsideLinkInfoByOsdCode() >>> 바인드("+(index-1)+") : ["+ osidInstiDstcd.trim() +"]");

            rs = this.executeQuery();

            while(rs.next())
            {
                vo = new OutsideLinkVO();

                vo.setSyslinkCode (rs.getString("SysLnkgDstcd"      ).trim());
                vo.setBatchCode   (rs.getString("BjobBzwkDstcd"     ).trim());
                vo.setOsdCode     (rs.getString("OsidInstiDstcd"    ).trim());
                vo.setReqResCode  (rs.getString("RqstRspnsDstcd"    ).trim());
                vo.setLinkIP      (rs.getString("LnkgIPInfoName"    ).trim());
                vo.setLinkPort    (rs.getString("LnkgPortInfoName"  ).trim());
                vo.setUserID      (rs.getString("LnkgID"            ).trim());
                vo.setPwd         (rs.getString("LnkgPwd"           ).trim());
                vo.setToVal       (rs.getInt   ("ToutVal"           ));
                vo.setLinkStatus  (rs.getString("TCirtLnkgStusCd"   ).trim());
                vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName").trim());
                vo.setAdpName     (rs.getString("AdptrBzwkName"     ).trim());

//                logger.debug("  - ["+ vo.getBatchCode() +"] ["+ vo.getOsdCode() +"] ["+ vo.getReqResCode() +"] ["+ vo.getLinkPort() +"] ["+ vo.getLinkIP() +"]");
                al.add(vo);
            }
        } catch(Exception e) {
            throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS002"));
        } finally {
            this.disconnect();
        }
        return al;
    }
}