package com.kbstar.eai.flowcontrol.action;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.eactive.eai.flowcontrol.action.RouteActionException;
import com.eactive.eai.flowcontrol.action.RouteActionSupport;

public class CMBSRouteAction extends RouteActionSupport  {
	
	// 2009.02.13 정길영과장 요청사항
	// CMBS용 라우팅 Action
	// <InData ... mode="$Key" ... />
	// mode 값을 추출한다.
	// 
	public String[] getRouteKeys(byte[] message) throws Exception {
		
		String[] keys = new String[1];
//		int keyIndex = 0;

		String xml = "<?xml version=\"1.0\" encoding=\"EUC-KR\"?><Message>"+new String(message)+"</Message>";
		DocumentBuilder builder = null;
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	        ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
	        Document doc = builder.parse(bis);
	        Element root = doc.getDocumentElement();

            NodeList lst = root.getChildNodes();
            
        	Node n = null;
			String nodeName = "";
			for(int i=0;i<lst.getLength();i++) {
				n = lst.item(i);
				nodeName = n.getNodeName();
                if( "InData".equals(nodeName) ) {
                	if(n.hasAttributes()) {
            			Node aNode = ((Element)n).getAttributeNode("mode");
            			if(aNode != null && aNode.getNodeType() == Node.ATTRIBUTE_NODE) {
            				keys[0] = ((Attr)aNode).getValue();
            			}
                	}
				}
			}
		} catch(Exception e) {
			throw new RouteActionException(this.getClass().getName() +" Error Extract Key : " +xml +" - " +e.getMessage());
		}
		if(keys[0] == null || keys[0].length() == 0) {
			throw new RouteActionException(this.getClass().getName() +" GCMS mode not found Error : value ["+keys[0]+"]");
		}
        return keys;        
	}
	
	public String getDescription() {
		return "키추출방식 : <InData ... mode=\"$Key\" ... />";
	}
}
