package com.eactive.eai.common.web;

import com.eactive.eai.common.dao.Keys;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 1. 기능 : 관리자화면에서 select Tag를 생성해주는 Custom Tag Class 
 * 2. 처리 개요 : 필드 추출 Rule 정보테이블에 대한 Create, Read, Update, Delete 를 처리한다.
 * <kbeai:MakeSelectData dataSource="" table="" value="" label="" id="" /> 
 *
 * @author :
 * @version : v 1.0.0
 * @see :
 * @since : :
 */

public class MakeSelectDataTag extends BodyTagSupport {
	private String dataSource;
	private String table;
	private String where;
	private String value;
	private String label;
//    private String type;

	public void setDataSource(String dataSource) {
		this.dataSource = dataSource;
	}

	public void setTable(String table) {
		this.table = Keys.TABLE_OWNER + table;
	}

	public void setWhere(String where) {
		this.where = where;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setLabel(String label) {
		this.label = label;
	}

//    public void setType(String type) {
//        this.type = type;    
//    }

	public int doStartTag() throws JspTagException {
		if (dataSource == null) {
			return SKIP_BODY;
		}
		try {
			pageContext.setAttribute(id, selectFromTable(), PageContext.PAGE_SCOPE);
		} catch (Exception e) {
			throw new JspTagException(e.toString());
		}
		return EVAL_BODY_TAG;
	}

	public int doEndTag() throws JspTagException {

		try {
			if (bodyContent != null)
				bodyContent.writeOut(bodyContent.getEnclosingWriter());
		} catch (java.io.IOException e) {
			throw new JspTagException("IO Error: " + e.toString());
		}
		return EVAL_PAGE;
	}

	/**
	 * 1. 기능 : 입력받은 Tag Value를 통해 html select Tag를 생성하기 위한 KEY, VALUE를 조회한다. 2. 처리
	 * 개요 : Query를 생성하여 설정된 DataSource를 통해 key, value를 조회한다. 3. 주의사항
	 *
	 * @return HashMap label, value 쌍을 가진 HashMap
	 * @exception Excepiton SQLException
	 **/

	public Map selectFromTable() throws Exception {
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = getConnection();
			StringBuffer query = new StringBuffer();
			query.append("select ").append(label).append(", ").append(value).append(" ").append(" from ").append(table)
					.append(" ");
			if (where != null) {
				query.append("where ").append(where).append(" ");
			}
			query.append("order by ").append(label);

//            System.out.println("query>> "+query.toString());
			stmt = con.prepareStatement(query.toString());
			rs = stmt.executeQuery();

			Map map = new LinkedHashMap();
			while (rs.next()) {
				map.put(rs.getString(1), rs.getString(2));
			}
			return map;
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (Exception e) {
			}
			try {
				if (stmt != null)
					stmt.close();
			} catch (Exception e) {
			}
			try {
				if (con != null)
					con.close();
			} catch (Exception e) {
			}
		}
	}

	public Connection getConnection() throws Exception {
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup(dataSource);
			return ds.getConnection();
		} catch (Exception e) {
			throw e;
		}
	}
}
