/* $Id: SubprocessActivityInspector.java,v 1.2 2007/12/11 09:54:58 nito Exp $
 * 
 * Copyright (c)ARGO 21, Corporation. 2005, 2006.  All rights reserved.
 * 
 * This file is part of Nautica Workflow.
 * 
 *  Nautica Workflow is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 * 
 *  Nautica Workflow is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with Nautica Workflow; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *  
 */
package jp.co.argo21.nautica.tool.wfd.inspector;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import jp.co.argo21.nautica.commons.swing.ByteLimitedDocument;
import jp.co.argo21.nautica.commons.swing.DialogUtilities;
import jp.co.argo21.nautica.commons.swing.NumericDocument;
import jp.co.argo21.nautica.commons.util.ResourceManager;
import jp.co.argo21.nautica.commons.util.StringUtils;
import jp.co.argo21.nautica.tool.wfd.DesktopPane;
import jp.co.argo21.nautica.tool.wfd.ElementReceivableView;
import jp.co.argo21.nautica.tool.wfd.InspectorDialog;
import jp.co.argo21.nautica.tool.wfd.ProcessDesignFrame;
import jp.co.argo21.nautica.tool.wfd.WorkflowDesignerConstants;
import jp.co.argo21.nautica.tool.wfd.WorkflowDesignerManager;
import jp.co.argo21.nautica.tool.wfd.element.ActivityElement;
import jp.co.argo21.nautica.tool.wfd.element.Element;
import jp.co.argo21.nautica.tool.wfd.element.PackageElement;
import jp.co.argo21.nautica.tool.wfd.element.ProcessElement;
import jp.co.argo21.nautica.tool.wfd.element.VariableElement;

/**
 * サブプロセスアクティビティ用のインスペクタ画面
 * 
 * @author  Norihiro Itoh(ARGO 21 Corp.)
 * @version $Revision: 1.2 $
 * @since   Nautica Workflow 1.0
 */
public class SubprocessActivityInspector extends TransitionalActivityInspector
{
	/** シリアルバージョンID */
	private static final long serialVersionUID = 1L;

	/** 実行期限表示エリア */
	private JTextField limitField;
	/** 単位表示エリア */
	private JLabel unitField;

	/** サブプロセス表示エリア */
	private ElementReceivableView subprocIconField;
	/** サブプロセスID表示エリア */
	private JLabel subprocIDField;
	/** サブプロセス名表示エリア */
	private JLabel subprocNameField;
	/** パラメータリスト */
	private JTable paramTable;
	/** 変数表示エリア */
	private ElementReceivableView varIconField;
	/** 解除ボタン */
	private JButton unbindButton;
	/** 同期処理ボタン */
	private JRadioButton syncButton;
	/** 非同期処理ボタン */
	private JRadioButton asyncButton;
	/** エンジン名エリア */
	private JTextField engineField;
	
	/**  */
	private ParamMappingTableModel paramModel;

	/**  */
	private ChangeProcessElementAction changeProcAction;
	/**  */
	private ChangeVariableElementAction changeVarAction;

	/**  */
	private ProcessElement subproc;

	/**
	 * 対話型アクティビティ用のインスペクタ画面を生成する。
	 */
	public SubprocessActivityInspector()
	{
		super();
		
		ResourceManager rm = WorkflowDesignerManager.getResourceManager();

		changeProcAction = new ChangeProcessElementAction();
		changeVarAction = new ChangeVariableElementAction();

		JPanel panel1 = createLimitInfoPanel(rm);
		addTab(rm.getResource("SubprocessActivityInspector.tab.0"), panel1);
		JPanel panel2 = createSubprocessInfoPanel(rm);
		addTab(rm.getResource("SubprocessActivityInspector.tab.1"), panel2);

		validate();
	}
	
	/**
	 * 基本情報のパネルを生成する。
	 * 
	 * @param rm リソースマネージャ
	 * @return パネル
	 */
	private JPanel createLimitInfoPanel(ResourceManager rm)
	{
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
		Dimension size = new Dimension(380, 50);
		panel.setSize(size);
		panel.setPreferredSize(size);
		JLabel l0 = new JLabel(rm.getResource("SubprocessActivityInspector.label.0"));

		limitField = new JTextField();
		limitField.setHorizontalAlignment(SwingConstants.RIGHT);
		limitField.setDocument(new NumericDocument(3, true, true));
		unitField = new JLabel();

		panel.add(locate(l0,                  10,  10, 100, 25));
		panel.add(locate(limitField,         110,  10,  70, 25));
		panel.add(locate(unitField,          180,  10,  70, 25));

		validate();
		
		return panel;
	}
	
	/**
	 * 基本情報のパネルを生成する。
	 * 
	 * @param rm リソースマネージャ
	 * @return パネル
	 */
	private JPanel createSubprocessInfoPanel(ResourceManager rm)
	{
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
		Dimension size = new Dimension(380, 420);
		panel.setSize(size);
		panel.setPreferredSize(size);
		JLabel l0 = new JLabel(rm.getResource("SubprocessActivityInspector.label.1"));
		JLabel l1 = new JLabel(rm.getResource("SubprocessActivityInspector.label.2"));
		JLabel l2 = new JLabel(rm.getResource("SubprocessActivityInspector.label.3"));
		JLabel l3 = new JLabel(rm.getResource("SubprocessActivityInspector.label.4"));
		JLabel l4 = new JLabel(rm.getResource("SubprocessActivityInspector.label.5"));
		JLabel l5 = new JLabel(rm.getResource("SubprocessActivityInspector.label.6"));

		subprocIconField = new ElementReceivableView(WorkflowDesignerConstants.EL_PROCESS);
		subprocIconField.addChangeElementListener(changeProcAction);
		subprocIDField = new JLabel();
		subprocIDField.setBorder(border);
		subprocNameField = new JLabel();
		subprocNameField.setBorder(border);
		paramModel = new ParamMappingTableModel();
		paramTable = new JTable(paramModel);
		paramTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		ListSelectionModel selectModel= paramTable.getSelectionModel();
		selectModel.addListSelectionListener(new SelectParamTableAction());
		JScrollPane sp = new JScrollPane();
		sp.setViewportView(paramTable);
		varIconField = new ElementReceivableView(WorkflowDesignerConstants.EL_VARIABLE);
		varIconField.addChangeElementListener(changeVarAction);
		unbindButton = new JButton(rm.getResource("JButton.label.unbind"));
		unbindButton.addActionListener(new UnbindParamAction());
		syncButton = new JRadioButton(rm.getResource("SubprocessActivityInspector.label.7"));
		asyncButton = new JRadioButton(rm.getResource("SubprocessActivityInspector.label.8"));
		engineField = new JTextField();
		engineField.setDocument(new ByteLimitedDocument(64));

		syncButton.setSelected(true);

		ButtonGroup group = new ButtonGroup();
		group.add(syncButton);
		group.add(asyncButton);

		panel.add(locate(l0,                10,  10, 100,  25));
		panel.add(locate(subprocIconField,  10,  40,  60,  60));
		panel.add(locate(l1,                80,  42, 100,  25));
		panel.add(locate(l2,                80,  72, 100,  25));
		panel.add(locate(subprocIDField,   180,  42, 190,  25));
		panel.add(locate(subprocNameField, 180,  72, 190,  25));
		panel.add(locate(l3,                10, 100, 250,  25));
		panel.add(locate(sp,                10, 130, 270, 160));
		panel.add(locate(varIconField,     300, 130,  60,  60));
		panel.add(locate(unbindButton,     290, 200,  80,  25));
		panel.add(locate(l4,                10, 290, 100,  25));
		panel.add(locate(syncButton,        10, 320, 100,  25));
		panel.add(locate(asyncButton,      140, 320, 100,  25));
		panel.add(locate(l5,                10, 350, 100,  25));
		panel.add(locate(engineField,       10, 380, 200,  25));

		validate();
		
		return panel;
	}
	
	/**
	 * 編集された情報をアクティビティ要素に反映する。
	 * 
	 * @see jp.co.argo21.nautica.tool.wfd.inspector.Inspector#commit()
	 */
	public void commit()
	{
		super.commit();
		Element e = getInspectable();
		if (e != null) {
			if (e instanceof ActivityElement) {
				ActivityElement act = (ActivityElement)e;
				try {
					int limit = Integer.parseInt(limitField.getText());
					act.setLimit(limit);
				} catch (Exception ex) {
					act.setLimit(0);
				}
				if (subproc != null) {
					act.setSubprocessID(subproc.getID());
					//引数の設定
					act.getSubprocessParameters().clear();
					for (MappedParam mp : paramModel.getAllMappedParams()) {
						VariableElement v = mp.getActualParam();
						if (v == null) act.addSubprocessParameterID("");
						else act.addSubprocessParameterID(v.getID());
					}
					act.setEngineName(engineField.getText());
				} else {
					act.setSubprocessID(null);
					act.getSubprocessParameters().clear();
				}
				if (asyncButton.isSelected()) {
					act.setExecution(ActivityElement.ASYNCHR);
				} else {
					act.setExecution(ActivityElement.SYNCHR);
				}
				
			}
		}		
	}
	
	/**
	 * アクティビティ要素の情報をインスペクタに反映する。
	 * 
	 * @param elem アクティビティ要素
	 * @see jp.co.argo21.nautica.tool.wfd.inspector.Inspector#setInspectable(jp.co.argo21.nautica.tool.wfd.element.Element)
	 */
	public final void setInspectable(Element elem)
	{
		super.setInspectable(elem);

		if (elem != null) {
			DesktopPane desktop = WorkflowDesignerManager.getMainFrame().getDesktop();
			ProcessDesignFrame frame = desktop.getCurrentProcessDesignFrame();
		
			if (frame == null) return;
		
			if (elem instanceof ActivityElement) {
				updateDurationUnit(null);
				PackageElement pkg = WorkflowDesignerManager.getMainFrame().getPackage();
				ActivityElement act = (ActivityElement)elem;
				limitField.setText("" + act.getLimit());
				String pid = act.getSubprocessID();
				if (StringUtils.checkNull(pid) == false) {
					for (ProcessElement e : pkg.getProcesses()) {
						if (pid.equals(e.getID())) {
							subproc = e;
							break;
						} 
					}
					subprocIconField.setElement(subproc);
					updateProcessInfo();
					if (subproc != null) {
						//引数のロード
						List<String> params = act.getSubprocessParameters();
						for (int i = 0; i < params.size(); i++) {
							String vid = (String)params.get(i);
							if (StringUtils.checkNull(vid) == false) {
								for (VariableElement e : pkg.getVariables()) {
									if (vid.equals(e.getID())) {
										paramModel.updateMapping(i, e);
										break;
									} 
								}
							}
						}
						engineField.setText(act.getEngineName());
					}
				}
				if (act.getExecution() == ActivityElement.ASYNCHR) {
					asyncButton.setSelected(true);
				} else {
					syncButton.setSelected(true);
				}
			}
		}
	}

	/**
	 * インスペクタを初期化する。
	 * 
	 * @see jp.co.argo21.nautica.tool.wfd.inspector.Inspector#init()
	 */
	public void init()
	{
		super.init();
		
		limitField.setText("0");
		unitField.setText("");
		subprocIDField.setText("");
		subprocNameField.setText("");
		subprocIconField.setElement(null);
		varIconField.setElement(null);
		syncButton.setSelected(true);
		paramModel.clearAllParams();
		subproc = null;
		engineField.setText("");

		InspectorDialog.addChangeElementListener(WorkflowDesignerConstants.EL_PROCESS, changeProcAction);
		InspectorDialog.addChangeElementListener(WorkflowDesignerConstants.EL_VARIABLE, changeVarAction);
	}

	/**
	 * インスペクタのアンロードを行う。
	 * 
	 * @see jp.co.argo21.nautica.tool.wfd.inspector.Inspector#unload()
	 */
	public void unload()
	{
		InspectorDialog.removeChangeElementListener(WorkflowDesignerConstants.EL_PROCESS, changeProcAction);
		InspectorDialog.removeChangeElementListener(WorkflowDesignerConstants.EL_VARIABLE, changeVarAction);
	}

	/**
	 * プロセス情報を更新する。
	 */	
	private void updateProcessInfo()
	{
		if (subproc != null) {
			subprocIDField.setText(subproc.getID());
			subprocNameField.setText(subproc.getName());
			paramModel.initParams(subproc.getParameters());
		}
	}

	/**
	 * 期間単位を更新する。
	 * 
	 * @param p	プロセス
	 */	
	private void updateDurationUnit(ProcessElement p)
	{
		ProcessElement proc = p;
		if (proc == null) {
			DesktopPane desktop = WorkflowDesignerManager.getMainFrame().getDesktop();
			ProcessDesignFrame frame = desktop.getCurrentProcessDesignFrame();
		
			if (frame == null) return;
		
			proc = frame.getProcess();
		}
		int u = proc.getDurationUnit();
		if (u == ProcessElement.YEAR) {
			unitField.setText(ProcessInspector.DURATION_UNITS[0]);
		} else if (u == ProcessElement.MONTH) {
			unitField.setText(ProcessInspector.DURATION_UNITS[1]);
		} else if (u == ProcessElement.DAY) {
			unitField.setText(ProcessInspector.DURATION_UNITS[2]);
		} else if (u == ProcessElement.HOUR) {
			unitField.setText(ProcessInspector.DURATION_UNITS[3]);
		} else if (u == ProcessElement.MINUTE) {
			unitField.setText(ProcessInspector.DURATION_UNITS[4]);
		} else if (u == ProcessElement.SECOND) {
			unitField.setText(ProcessInspector.DURATION_UNITS[5]);
		} else {
			unitField.setText(ProcessInspector.DURATION_UNITS[2]);
		}
	}

	/**
	 * 変数情報を更新する。
	 */	
	private void updateVariableInfo()
	{
		paramModel.fireTableDataChanged();
	}

	/**
	 * 変数情報を更新する。
	 * 
	 * @param var	変数
	 */	
	private void updateVariableInfo(VariableElement var)
	{
		ResourceManager rm = WorkflowDesignerManager.getResourceManager();

		int selected = paramTable.getSelectedRow();
		if (selected < 0) {
			DialogUtilities.showWarning(rm.getResource("message.warn.0002"));
			varIconField.setElement(null);
			return;
		}
		if (var != null) {
			if (var.isInitialized() == false) {
				DialogUtilities.showError(rm.getResource("message.error.0028"));
				varIconField.setElement(null);
				return;
			}
			MappedParam mp = paramModel.getMappedParam(selected);
			int ptype = mp.getParam().getType();
			int aptype = var.getType();
			if (ptype != aptype) {
				DialogUtilities.showError(rm.getResource("message.error.0029"));
				varIconField.setElement(null);
				return;
			}
			paramModel.updateMapping(selected, var);
		}
		paramModel.fireTableRowsUpdated(selected, selected);
		varIconField.setElement(null);
	}

	/**
	 * マッピングを解除する。
	 */	
	private void unbindSelectedMapping()
	{
		ResourceManager rm = WorkflowDesignerManager.getResourceManager();

		int selected = paramTable.getSelectedRow();
		if (selected < 0) {
			DialogUtilities.showWarning(rm.getResource("message.warn.0002"));
			varIconField.setElement(null);
			return;
		}
		paramModel.removeMapping(selected);
		varIconField.setElement(null);
	}

	/**
	 * 変数アイコンを表示する。
	 */	
	private void showVariableIcon()
	{
		//ResourceManager rm = WorkflowDesignerManager.getResourceManager();

		int selected = paramTable.getSelectedRow();
		if (selected < 0) return;
		
		MappedParam mp = paramModel.getMappedParam(selected);
		if (mp != null) {
			varIconField.setElement(mp.getActualParam());
		}
	}
	
	/**
	 * パラメータを選択した場合の処理。
	 */	
	class SelectParamTableAction implements ListSelectionListener
	{
		/**
		 * 変数アイコンを表示する。
		 * 
		 * @param e	イベント
		 * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
		 */
		public void valueChanged(ListSelectionEvent e)
		{
			showVariableIcon();
		}
	}
	
	/**
	 * マッピングの解除を選択した場合の処理。
	 */	
	class UnbindParamAction implements ActionListener
	{
		/**
		 * マッピングを解除する。
		 * 
		 * @param e	イベント
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		public void actionPerformed(ActionEvent e)
		{
			unbindSelectedMapping();
		}
	}

	/**
	 * プロセスが変更された場合の処理
	 */	
	class ChangeProcessElementAction implements ChangeElementListener
	{
		/**
		 * 変更を反映する。
		 * 
		 * @param elem	プロセス
		 * @see jp.co.argo21.nautica.tool.wfd.dnd.DropElementListener#elementDropped(jp.co.argo21.nautica.tool.wfd.element.Element)
		 */
		public void elementChanged(Element elem)
		{
			updateProcessInfo();
			updateDurationUnit((ProcessElement)elem);
		}

		/**
		 * プロセスがドロップされた場合の処理
		 * 
		 * @param elem	プロセス
		 * @see jp.co.argo21.nautica.tool.wfd.dnd.DropElementListener#elementDropped(jp.co.argo21.nautica.tool.wfd.element.Element)
		 */
		public void elementDropped(Element elem)
		{
			if (elem instanceof ProcessElement) {
				subproc = (ProcessElement)elem;
				updateProcessInfo();
			}
		}
	}

	/**
	 * 変数が変更された場合の処理
	 */	
	class ChangeVariableElementAction implements ChangeElementListener
	{
		/**
		 * 変数の変更を反映する。
		 * 
		 * @param elem	変数
		 * @see jp.co.argo21.nautica.tool.wfd.dnd.DropElementListener#elementDropped(jp.co.argo21.nautica.tool.wfd.element.Element)
		 */
		public void elementChanged(Element elem)
		{
			updateVariableInfo();
		}

		/**
		 * 変数がドロップされた場合の処理。
		 * 
		 * @param elem	変数
		 * @see jp.co.argo21.nautica.tool.wfd.dnd.DropElementListener#elementDropped(jp.co.argo21.nautica.tool.wfd.element.Element)
		 */
		public void elementDropped(Element elem)
		{
			if (elem instanceof VariableElement) {
				updateVariableInfo((VariableElement)elem);
			}
		}
	}
}
