/**
 *
 */
package control;

import java.io.IOException;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import model.Account;
import model.ClassAccount;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import system.ClassColumnMaster;
import system.ColumnMaster;

import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import common.DBAccessWrapper;
import common.DecoratedEntity;
import common.Environment;

/**
 *
 * @author 無糖ブラック
 *
 */
public class AccountManager extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String characterEncoding = "UTF-8";
		request.setCharacterEncoding(characterEncoding);

		String contentType = "text/html; charset=UTF-8";
		response.setContentType(contentType);

		String envPath = getServletContext().getRealPath("/conf/env.ini");
		Environment env = Environment.getEnvironment();
		env.init(envPath);
		DBAccessWrapper db = new DBAccessWrapper(env);

		HttpSession session = request.getSession(false);
		String in_tableid = request.getParameter("tableid");
		if(in_tableid == null) {
			return;
		}
		String in_userid = (String)session.getAttribute("userid");
		if(in_userid == null) {
			return;
		}

		try {

			String conditionMaster = "";
			String conditionSetting = "";
			ArrayList<String> conditionTypes = new ArrayList<String>();
			ArrayList<Object> conditionValues = new ArrayList<Object>();

			conditionMaster = "self.TABLE_ID = ?";
			conditionSetting = "self.USER_NUMBER = ?";
			conditionTypes.clear();
			conditionTypes.add("string");
			conditionTypes.add("string");
			conditionValues.clear();
			conditionValues.add(in_tableid);
			conditionValues.add(in_userid);

			db.connect();
			ClassColumnMaster clsColumnMaster = new ClassColumnMaster(db);
			ArrayList<DecoratedEntity> objects = clsColumnMaster.selectWithColumnSetting(conditionMaster, conditionSetting, conditionTypes, conditionValues);

			String condition = "";
			conditionTypes.clear();
			conditionValues.clear();

			ArrayList<Account> accounts;
			ClassAccount clsAccount = new ClassAccount(db);
			accounts = clsAccount.select(condition, conditionTypes, conditionValues);
			db.close();

			// XML作成
			DocumentBuilder documentBuilder = null;
			documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = documentBuilder.newDocument();

			Element elem_rows = document.createElement("rows");
			document.appendChild(elem_rows);

			Iterator<Account> itrAccount = accounts.iterator();
			while (itrAccount.hasNext()) {
				Account account = itrAccount.next();

				Element elem_row = null;
				Element elem_cell = null;

				String identification = account.identification();
				elem_row = document.createElement("row");
				elem_row.setAttribute("id", identification);
				elem_rows.appendChild(elem_row);

				Iterator<DecoratedEntity> itrColumns = objects.iterator();
				while (itrColumns.hasNext()) {
					DecoratedEntity decoratedEntity = itrColumns.next();

					ColumnMaster columnMaster = (ColumnMaster) decoratedEntity.originator;
					//ColumnSetting columnSetting = (ColumnSetting) decoratedEntity.decorator;

					String columnId = columnMaster.getProperties("COLUMN_ID");
					String cellString = account.getProperties(columnId);
					elem_cell = document.createElement("cell");
					elem_cell.appendChild(document.createTextNode(cellString));
					elem_row.appendChild(elem_cell);
				}

				// Level
				elem_cell = document.createElement("cell");
				elem_cell.appendChild(document.createTextNode("1"));
				elem_row.appendChild(elem_cell);

				// Parent
				elem_cell = document.createElement("cell");
				elem_cell.appendChild(document.createTextNode(""));
				elem_row.appendChild(elem_cell);

				// IsLeaf
				elem_cell = document.createElement("cell");
				elem_cell.appendChild(document.createTextNode("false"));
				elem_row.appendChild(elem_cell);
			}

			// XML出力
			TransformerFactory tf = TransformerFactoryImpl.newInstance();
			tf.setAttribute(TransformerFactoryImpl.INDENT_NUMBER, "2");

			Transformer transformer = tf.newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(OutputKeys.METHOD, "xml");

			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);

			DOMSource source = new DOMSource(document);
			transformer.transform(source, result);

			response.getWriter().println(writer.toString());

		} catch (SQLException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}
}
