/*
 * Copyright (c) 2007, Going Dot Com Inc. All rights reserved.
 */

package jp.co.going.xbrl.sample;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.tree.TreePath;

import jp.co.going.xbrl.common.XbException;
import jp.co.going.xbrl.sample.dao.XbContextScenarioDao;
import jp.co.going.xbrl.sample.dao.XbEtcDao;
import jp.co.going.xbrl.sample.dao.obj.XbEtcObj;
import jp.co.going.xbrl.sample.dao.obj.XbMainEtcObj;

/**
 * @author Masako Okayasu
 */
@SuppressWarnings("serial")
public class XbContextScenarioInput extends XbTreeDataSet implements ActionListener {

	private Connection conn = null;
	private XbEtcDao etcDao = null;
	private XbContextScenarioDao contextScenarioDao = null;

	private String[] dataList = null;
	private XbMyTreeNode rootNode = new XbMyTreeNode("（登録済リスト）");
	private JButton expButton = new JButton("展開");

	private long contextID = 0;
	private String prefix = "";
	private String uri = "";

	/**
	 * コンストラクタ
	 */
	public XbContextScenarioInput(Connection conn, long contextID) {
		this.conn = conn;
		this.contextID = contextID;

		setTitle("XBRL Toolkit : Input " + CONTEXT);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}

		etcDao = XbEtcDao.getInstance(conn);
		contextScenarioDao = XbContextScenarioDao.getInstance(conn);


		Container container = getContentPane();
		container.setLayout(new BorderLayout());

		JPanel ScenarioPanel = ScenarioPanel();
		JPanel SubmitPanel = SubmitPanel();

		submitButton.addActionListener(this);
		submitButton.setEnabled(false);
		closeButton.addActionListener(this);

		container.add(ScenarioPanel, BorderLayout.NORTH);
		container.add(SubmitPanel, BorderLayout.SOUTH);

		try {
			// Scenarioの初期値
			ArrayList<XbEtcObj> scenarioList = etcDao.selectAll(etcType.get(SCENARIO));
			dataList = new String[scenarioList.size()];
			for(int i=0; i<scenarioList.size(); i++) {
				XbEtcObj etc = scenarioList.get(i);
				dataList[i] = etc.getEtc_id() + ". " + etc.getEtc_name();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		pack();
	}

	/**
	 * Scenarioツリーの生成
	 */
	private JPanel ScenarioPanel() {
		JPanel ScenarioPanel = new JPanel();
		ScenarioPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
		ScenarioPanel.setLayout(new BorderLayout());

		JLabel title = new JLabel("　【 " + nameList.get(SCENARIO) + " <" + SCENARIO + "> 】");
		ScenarioPanel.add(title, BorderLayout.WEST);

		expButton.addActionListener(this);
		ScenarioPanel.add(setPanel(expButton), BorderLayout.EAST);

		ScenarioPanel.add(TreePanel(SCENARIO, rootNode, contextID, true, conn), BorderLayout.SOUTH);

		return ScenarioPanel;
	}

	/**
	 * Button のイベントを取得。
	 */
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();

		// シナリオ部分のPopMenuAction
		treePopMenuAction(source, dataList);

		if(source == submitButton){
			try {
				getNodeValue(rootNode);
				conn.commit();

				JOptionPane.showMessageDialog(this, "データを登録しました。");
				submitButton.setEnabled(false);

			} catch (Exception ex) { 
				ex.printStackTrace();
		}	}
		else if(source == closeButton){
			this.dispose();
		}

		treeModel.reload();
		tree.expandPath(new TreePath(selectNode));
		tree.setSelectionPath(new TreePath(selectNode.getPath()));
		selectNode = (XbMyTreeNode)tree.getLastSelectedPathComponent();

		if(source == expButton) {
			for(int i=0; i<tree.getRowCount(); i++) {
				tree.expandRow(i);
			}
		}
	}

	/**
	 * Context - Scenario 情報を登録
	 */
	private void getNodeValue(XbMyTreeNode Node) {
		try {
			for(int i=0; i<Node.getChildCount(); i++) {
				XbMyTreeNode childNode = (XbMyTreeNode)Node.getChildAt(i);
				String childNodeName = childNode.getUserObject().toString();

				// Context - Scenario 登録
				if(childNodeName.indexOf("<" + SCENARIO + ">： ") != -1) {
					String temp = childNodeName.substring(childNodeName.indexOf("Prefix=")+7).replace("\"", "");
					prefix = temp.substring(0, temp.indexOf("　"));
					uri = temp.substring(temp.indexOf("　URI=")+5);
				}
				else if(childNode.getID() > 0) {

					// レコードの存在確認
					XbMainEtcObj mainEtcObj = contextScenarioDao.select(contextID, Node.getID(), childNode.getID(), prefix); 

					if(mainEtcObj==null) {
						mainEtcObj = new XbMainEtcObj();
						mainEtcObj.setMain_id(contextID);
						mainEtcObj.setEtc_type(etcType.get(SCENARIO));
						mainEtcObj.setEtc_id(childNode.getID());
						mainEtcObj.setParent_etc_id(Node.getID());
						mainEtcObj.setPrefix(prefix);
						mainEtcObj.setUri(uri);
						mainEtcObj.setCreation_date(new Date());
						contextScenarioDao.insert(mainEtcObj);
				}	}

				// さらに深部へ
				if(childNode.getChildCount() > 0) {
					getNodeValue(childNode);
				}
			}
		} catch (XbException err) {
			try {
				err.printStackTrace();
				conn.rollback();
			}
			catch (Exception ex) {
				ex.printStackTrace();
			}
		} catch (Exception ex) { 
			ex.printStackTrace();
	}	}
}