/* $Id: AutomaticActivityInspector.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.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
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.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.ApplicationElement;
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.ParticipantElement;
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 AutomaticActivityInspector extends TransitionalActivityInspector
{
	/** シリアルバージョンID */
	private static final long serialVersionUID = 1L;

	/** 実行期限表示エリア */
	private JTextField limitField;
	/** 単位表示エリア */
	private JLabel unitField;
	/** 実行権限表示エリア */
	private ElementReceivableView performerIconField;
	/** 実行権限ID表示エリア */
	private JLabel performerIDField;
	/** 実行権限名表示エリア */
	private JLabel performerNameField;

	/** アプリケーション表示エリア */
	private ElementReceivableView appIconField;
	/** アプリケーションID表示エリア */
	private JLabel appIDField;
	/** アプリケーション名表示エリア */
	private JLabel appNameField;
	/** パラメータリスト */
	private JTable paramTable;
	/** 変数表示エリア */
	private ElementReceivableView varIconField;
	/** 解除ボタン */
	private JButton unbindButton;
	
	/** パラメータマッピング */
	private ParamMappingTableModel paramModel;
	
	/** プロセス変更処理 */
	private ChangeProcessElementAction changeProcAction;
	/** 実行許可者変更処理 */
	private ChangeParticipantElementAction changeParticipantAction;
	/** アプリケーション変更処理 */
	private ChangeApplicationElementAction changeAppAction;
	/** 変数変更処理 */
	private ChangeVariableElementAction changeVarAction;

	/** 実行許可者 */
	private ParticipantElement performer;
	/** アプリケーション */
	private ApplicationElement app;

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

		changeProcAction = new ChangeProcessElementAction();
		changeParticipantAction = new ChangeParticipantElementAction();
		changeAppAction = new ChangeApplicationElementAction();
		changeVarAction = new ChangeVariableElementAction();

		JPanel panel1 = createAutomaticInfoPanel(rm);
		addTab(rm.getResource("AutomaticActivityInspector.tab.0"), panel1);
		JPanel panel2 = createAppInfoPanel(rm);
		addTab(rm.getResource("AutomaticActivityInspector.tab.1"), panel2);

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

		limitField = new JTextField();
		limitField.setHorizontalAlignment(SwingConstants.RIGHT);
		limitField.setDocument(new NumericDocument(3, true, true));
		unitField = new JLabel();
		performerIconField = new ElementReceivableView(WorkflowDesignerConstants.EL_PARTICIPANT);
		performerIconField.addChangeElementListener(changeParticipantAction);
		performerIDField = new JLabel();
		performerIDField.setBorder(border);
		performerNameField = new JLabel();
		performerNameField.setBorder(border);

		panel.add(locate(l0,                  10,  10, 100, 25));
		panel.add(locate(limitField,         110,  10,  70, 25));
		panel.add(locate(unitField,          180,  10,  70, 25));
		panel.add(locate(l1,                  10,  40, 100, 25));
		panel.add(locate(performerIconField,  10,  70,  60, 60));
		panel.add(locate(l2,                  80,  72, 100, 25));
		panel.add(locate(l3,                  80, 102, 100, 25));
		panel.add(locate(performerIDField,   180,  72, 190, 25));
		panel.add(locate(performerNameField, 180, 102, 190, 25));

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

		appIconField = new ElementReceivableView(WorkflowDesignerConstants.EL_APPLICATION);
		appIconField.addChangeElementListener(changeAppAction);
		appIDField = new JLabel();
		appIDField.setBorder(border);
		appNameField = new JLabel();
		appNameField.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());

		panel.add(locate(l0,              10,  10, 100,  25));
		panel.add(locate(appIconField,    10,  40,  60,  60));
		panel.add(locate(l1,              80,  42, 100,  25));
		panel.add(locate(l2,              80,  72, 100,  25));
		panel.add(locate(appIDField,     180,  42, 190,  25));
		panel.add(locate(appNameField,   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));

		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 (performer != null) {
					act.setPerformerID(performer.getID());
				} else {
					act.setPerformerID(null);
				}
				if (app != null) {
					act.setApplicationID(app.getID());
					//引数の設定
					act.getApplicationParameters().clear();
					for (MappedParam mp : paramModel.getAllMappedParams()) {
						VariableElement v = mp.getActualParam();
						if (v == null) act.addApplicationParameterID("");
						else act.addApplicationParameterID(v.getID());
					}
				} else {
					act.setApplicationID(null);
					act.getApplicationParameters().clear();
				}
			}
		}		
	}
	
	/**
	 * アクティビティ要素の情報をインスペクタに反映する。
	 * 
	 * @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) {
			if (elem instanceof ActivityElement) {
				PackageElement pkg = WorkflowDesignerManager.getMainFrame().getPackage();
				updateDurationUnit(null);
				ActivityElement act = (ActivityElement)elem;
				limitField.setText("" + act.getLimit());
				String pfid = act.getPerformerID();
				if (StringUtils.checkNull(pfid) == false) {
					for (ParticipantElement e : pkg.getParticipants()) {
						if (pfid.equals(e.getID())) {
							performer = e;
							break;
						} 
					}
					performerIconField.setElement(performer);
					updatePerformerInfo();
				}
				String aid = act.getApplicationID();
				if (StringUtils.checkNull(aid) == false) {
					for (ApplicationElement e : pkg.getApplications()) {
						if (aid.equals(e.getID())) {
							app = e;
							break;
						} 
					}
					appIconField.setElement(app);
					updateApplicationInfo();
					if (app != null) {
						//引数のロード
						List<String> params = act.getApplicationParameters();
						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;
									} 
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * インスペクタを初期化する。
	 * 
	 * @see jp.co.argo21.nautica.tool.wfd.inspector.Inspector#init()
	 */
	public void init()
	{
		super.init();
		
		limitField.setText("0");
		unitField.setText("");
		performerIDField.setText("");
		performerNameField.setText("");
		appIDField.setText("");
		appNameField.setText("");
		performerIconField.setElement(null);
		appIconField.setElement(null);
		varIconField.setElement(null);
		paramModel.clearAllParams();
		performer = null;
		app = null;
		
		InspectorDialog.addChangeElementListener(WorkflowDesignerConstants.EL_PROCESS, changeProcAction);
		InspectorDialog.addChangeElementListener(WorkflowDesignerConstants.EL_PARTICIPANT, changeParticipantAction);
		InspectorDialog.addChangeElementListener(WorkflowDesignerConstants.EL_APPLICATION, changeAppAction);
		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_PARTICIPANT, changeParticipantAction);
		InspectorDialog.removeChangeElementListener(WorkflowDesignerConstants.EL_APPLICATION, changeAppAction);
		InspectorDialog.removeChangeElementListener(WorkflowDesignerConstants.EL_VARIABLE, changeVarAction);
	}

	/**
	 * 実行許可者を更新する。
	 */	
	private void updatePerformerInfo()
	{
		if (performer != null) {
			performerIDField.setText(performer.getID());
			performerNameField.setText(performer.getName());
		}
	}

	/**
	 * アプリケーションを更新する。
	 */	
	private void updateApplicationInfo()
	{
		if (app != null) {
			appIDField.setText(app.getID());
			appNameField.setText(app.getName());
			paramModel.initParams(app.getParameters());
		}
	}

	/**
	 * 変数を更新する。
	 */	
	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.fireTableDataChanged();
		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());
		}
	}

	/**
	 * 期間単位を更新する。
	 * 
	 * @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]);
		}
	}

	/**
	 * プロセス変更処理
	 */
	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)
		{
			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)
		{
		}
	}

	/**
	 * パラメータ選択処理
	 */	
	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 ChangeParticipantElementAction 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)
		{
			updatePerformerInfo();
		}

		/**
		 * 実行許可者のドロップを反映する。
		 * 
		 * @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 ParticipantElement) {
				performer = (ParticipantElement)elem;
				updatePerformerInfo();
			}
		}
	}

	/**
	 * アプリケーション変更処理
	 */
	class ChangeApplicationElementAction 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)
		{
			updateApplicationInfo();
		}

		/**
		 * アプリケーションのドロップを反映する。
		 * 
		 * @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 ApplicationElement) {
				app = (ApplicationElement)elem;
				updateApplicationInfo();
			}
		}
	}

	/**
	 * 変数変更処理
	 */
	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);
			}
		}
	}
}
