package cn.com.origin.autocode.classification.panels;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.MenuSelectionManager;
import javax.swing.SwingUtilities;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.InterfaceAIFOperationExecutionListener;
import com.teamcenter.rac.aifrcp.AifrcpPlugin;
import com.teamcenter.rac.classification.common.TCClassificationViewer;
import com.teamcenter.rac.classification.common.form.G4MUnitLabel;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.ics.ICSAutoFilterValue;
import com.teamcenter.rac.kernel.ics.ICSFormat;
import com.teamcenter.rac.kernel.ics.ICSPropertyDescription;
import com.teamcenter.rac.kernel.ics.ICSUnitDefinition;
import com.teamcenter.rac.kernel.ics.ICSUnitDefinitions;
import com.teamcenter.rac.kernel.ics.ICSView;
import com.teamcenter.rac.util.AbstractPopupButton;
import com.teamcenter.rac.util.Registry;
import com.teamcenter.rac.util.log.Debug;

//package com.teamcenter.rac.classification.common.form.G4MListValuesButton;
public class ListValuesButton extends AbstractPopupPanel implements InterfaceAIFOperationExecutionListener {

	ICSView icsView;
	ICSPropertyDescription aicspropertydescription;
	JComponent jComponent;
	JComponent jComponentLabel;

	private class ValueListBox extends JPanel implements ActionListener {
		public void actionPerformed(ActionEvent actionevent) {
			if (actionevent.getSource() == m_okbutton) {
				setSelectedValue();
				closeDialog();
			} else if (actionevent.getSource() == m_cancelbutton) {
				postDown();
				closeDialog();
			}
			 else if (actionevent.getSource() == m_clearbutton) {
				{
					if (jComponent instanceof JTextField) {
						JTextField textField = (JTextField) jComponent;
						textField.setText("");
					} else if (jComponent instanceof JComboBox) {
						JComboBox combox = (JComboBox) jComponent;
						combox.setSelectedItem("");
					}
					postDown();
					closeDialog();
				}
			}

		}

		private void setSelectedValue() {
			if ((m_list.getSelectedValue() instanceof String) || (jComponent instanceof JComboBox)) {
				clearUnitFromAttrField();
				postDown();
				return;
			}
			ICSAutoFilterValue icsautofiltervalue = (ICSAutoFilterValue) m_list.getSelectedValue();
			if (icsautofiltervalue != null) {
				if (jComponent instanceof JTextField) {
					JTextField textField = (JTextField) jComponent;
					textField.setText(icsautofiltervalue.getValue());
				} else if (jComponent instanceof JComboBox) {
					JComboBox combox = (JComboBox) jComponent;
					combox.setSelectedItem(icsautofiltervalue);
				}
				cleanMap(icsautofiltervalue.getValue());
				clearUnitFromAttrField();
				postDown();
			}
		}

		public void cleanMap(String s) {
			Object aobj[] = ListValuesButton.m_optStorageValuesMap.keySet().toArray();
			for (int i = 0; i < aobj.length; i++)
				if (aobj[i].toString().startsWith((new StringBuilder()).append(aicspropertydescription.getId()).append("_").toString()) && !aobj[i].toString().equals((new StringBuilder()).append(aicspropertydescription.getId()).append("_").append(s).toString()))
					ListValuesButton.m_optStorageValuesMap.remove(aobj[i].toString());

		}

		public void clearUnitFromAttrField() {
			if (aicspropertydescription.isAttributeNumericAndHasUnit()) {
				JTextField jtextfield = (JTextField) jComponent;
				char ac[] = jtextfield.getText().trim().toCharArray();
				String s = jtextfield.getText().trim();
				G4MUnitLabel g4munitlabel = (G4MUnitLabel) jComponentLabel;
				int i = 0;
				do {
					if (i >= ac.length)
						break;
					if (Character.isLetter(ac[i])) {
						ICSUnitDefinitions icsunitdefinitions = getSession().getClassificationService().getUnitDefinitions();
						g4munitlabel.setUnit(icsunitdefinitions, icsunitdefinitions.getUnitByIdOrLabel(s.substring(i).trim()).getId());
						String s1 = s.substring(0, i).trim();
						jtextfield.setText(s1);
						break;
					}
					i++;
				} while (true);
			}
		}

		public JList getList() {
			return m_list;
		}

		private JList m_list;
		JButton m_okbutton;
		JButton m_cancelbutton;
		JButton m_clearbutton;

		ValueListBox() {
			super(new BorderLayout());
			m_list = new JList();
			m_list.setSelectionMode(0);
			MouseAdapter mouseadapter = new MouseAdapter() {
				public void mouseClicked(MouseEvent mouseevent) {
					if (mouseevent.getClickCount() == 2)
						setSelectedValue();
				}
			};
			m_list.addMouseListener(mouseadapter);
			JScrollPane jscrollpane = new JScrollPane(m_list);
			add("Center", jscrollpane);

			JPanel jpanel = new JPanel();
			new BoxLayout(jpanel, 0);
			m_okbutton = new JButton("ok");
			m_okbutton.addActionListener(this);
			m_cancelbutton = new JButton("cancel");
			m_cancelbutton.addActionListener(this);
			m_clearbutton = new JButton("clear");
			m_clearbutton.addActionListener(this);
			jpanel.add(Box.createHorizontalGlue());
			jpanel.add(m_clearbutton);
			jpanel.add(Box.createHorizontalGlue());
			jpanel.add(m_cancelbutton);
			jpanel.add(m_okbutton);
			add("South", jpanel);
			this.setPreferredSize(new Dimension(250, 120));
		}
	}

	private class LoadValuesOperation extends AbstractAIFOperation {

		public void executeOperation() throws Exception {
			loadValues();
		}

	}

	private class ListValueRenderer extends JLabel implements ListCellRenderer {

		public Component getListCellRendererComponent(JList jlist, Object obj, int i, boolean flag, boolean flag1) {
			try {
				if (!obj.toString().equalsIgnoreCase("Loading Values...")) {
					ICSAutoFilterValue icsautofiltervalue = (ICSAutoFilterValue) obj;
					if (icsautofiltervalue.getFormat() != null && icsautofiltervalue.getFormat().isList()) {
						if (icsautofiltervalue.isDeprecated()) {
							setIcon(m_deprecateIcon);
							setText(icsautofiltervalue.getDisplayValue());
							setEnabled(false);
						} else {
							setIcon(null);
							setText(icsautofiltervalue.getDisplayValue());
						}
					} else if (icsautofiltervalue.isNative()) {
						if (icsautofiltervalue.getValue() != "" && icsautofiltervalue.getValue() != null) {
							if (icsautofiltervalue.isMetric())
								setIcon(m_metricIcon);
							else if (!icsautofiltervalue.isMetric())
								setIcon(m_nonMetricIcon);
							setText(icsautofiltervalue.getValue());
						}
					} else if (!icsautofiltervalue.isNative() && icsautofiltervalue.getValue() != "" && icsautofiltervalue.getValue() != null && icsautofiltervalue.getNativeValue() != "" && icsautofiltervalue.getNativeValue() != null) {
						if (icsautofiltervalue.isMetric())
							setIcon(m_metricIcon);
						else if (!icsautofiltervalue.isMetric())
							setIcon(m_nonMetricIcon);
						ICSUnitDefinition icsunitdefinition = getSession().getClassificationService().getUnitDefinitions().getUnitDefinition(aicspropertydescription.getAltUnit());
						String s = (new StringBuilder()).append(icsautofiltervalue.getValue()).append("  ").append("(").append(icsautofiltervalue.getNativeValue()).toString();
						if (icsunitdefinition != null)
							s = s.concat((new StringBuilder()).append(" ").append(icsunitdefinition.getLabel()).toString());
						setText((new StringBuilder()).append(s).append(")").toString());
					}
					if (flag) {
						setBackground(jlist.getSelectionBackground());
						setForeground(jlist.getSelectionForeground());
					} else if (icsautofiltervalue.isDeprecated()) {
						setForeground(jlist.getBackground().darker().darker());
						setBackground(jlist.getBackground());
					} else {
						setBackground(jlist.getBackground());
						setForeground(jlist.getForeground());
					}
					setEnabled(jlist.isEnabled());
				}
			} catch (Exception exception) {
				Debug.println((new StringBuilder()).append("An Error occured in G4MListValuesButton: ").append(exception).toString());
			}
			return this;
		}

		private ImageIcon m_metricIcon;
		private ImageIcon m_nonMetricIcon;
		private ImageIcon m_deprecateIcon;

		public ListValueRenderer() {
			super();
			m_metricIcon = Registry.getRegistry(TCClassificationViewer.class).getImageIcon("g4mAutoFilterButton.METRIC_ICON");
			m_nonMetricIcon = Registry.getRegistry(TCClassificationViewer.class).getImageIcon("g4mAutoFilterButton.NONMETRIC_ICON");
			m_deprecateIcon = Registry.getRegistry(TCClassificationViewer.class).getImageIcon("DeprecatedKeyLOVNode.ICON");
			setOpaque(true);
		}
	}

	public ListValuesButton(ICSView icsView, ICSPropertyDescription aicspropertydescription, JComponent jComponent, JComponent jComponentLabel) {
		this.icsView = icsView;
		this.aicspropertydescription = aicspropertydescription;
		this.jComponent = jComponent;
		this.jComponentLabel = jComponentLabel;
		m_optStorageValuesMap = new HashMap();
		if (m_icon == null)
			m_icon = Registry.getRegistry(TCClassificationViewer.class).getImageIcon("g4mAutoFilterButton.ICON");
		if (m_editIcon == null)
			m_editIcon = Registry.getRegistry(TCClassificationViewer.class).getImageIcon("g4mAutoFilterButton.EDIT_ICON");
		setIcon(m_icon);
		m_refOnEdit = aicspropertydescription.getExt1().length() != 0;
		setMargin(new Insets(0, 0, 0, 0));
		setFocusPainted(false);
		setPinnableButtonVisible(false);
		m_listPanel = new ValueListBox();
	}

	public void loadValues() {
		// if (m_form.getMode() == 1)
		// loadValues4search();
		// else
		loadValues4edit(icsView, aicspropertydescription);
	}

	public void loadValues4edit(ICSView icsView, ICSPropertyDescription icsPropertyDescription) {
		int i = 1;
		int ai[] = new int[i];
		String as[] = new String[i];
		int j = icsPropertyDescription.getId();
		String s = icsPropertyDescription.getExt1();
		if (s == null || s.length() == 0)
			s = icsView.getClassID();
		else
			j = -599;
		ai[0] = -600;
		as[0] = s;
		findValues(icsPropertyDescription, ai, as, j);
	}

	public TCSession getSession() {
		TCSession session = (TCSession) AifrcpPlugin.getSessionService().getDefaultSession();
		return session;
	}

	private void findValues(ICSPropertyDescription icsPropertyDescription, int ai[], String as[], int i) {
		try {
			m_optStorageValuesMap = new HashMap();
			com.teamcenter.rac.kernel.ics.ICSKeyLov icskeylov = null;
			if (icsPropertyDescription.getFormat().isList()) {
				icskeylov = icsPropertyDescription.getFormat().getKeyLov();
			}
			int j = icsView.getActiveUnitsystem();
			int m = icsView.getClassUnitSystem();
			int k = m;
			if (m == 0) {
				k = m;
			}
			if (m == 1) {
				k = m;
			}
			if (m == 2) {
				if (icsPropertyDescription.isAttributeNumericAndHasUnit()) {
					k = m;
				} else {
					k = j;
				}
			}
			// int j = m_form.getContext().getActiveUnitSystem();
			// int k = m_form.getContext().getSearchInUnitSys();
			// int l = m_form.getContext().getBaseView("Form").getClassUnitSystem();

			if (m != 2) {
				k |= 32;
			}

			if (icskeylov != null) {
				return;
			}
			m_values = getSession().getClassificationService().findValues(ai, as, j, k, i, icsPropertyDescription, icskeylov, m_optStorageValuesMap);

		} catch (TCException tcexception) {
			tcexception.printStackTrace();
		}
	}

	private boolean isSearchExpression(String s) {
		return s != null && !s.equals("") && s.substring(0, 1).matches("[<>!]");
	}

	public void setMode(int i) {
		setVisible(i != 2);
		if (m_refOnEdit && (i == 4 || i == 8))
			setIcon(m_editIcon);
		else
			setIcon(m_icon);
	}

	public void initPopupWindow() {
		try {
			getPanel().add(m_listPanel);
		} catch (Exception exception) {
			System.out.println((new StringBuilder()).append("G4MTreeSearchClassPanel() throws ").append(exception).toString());
		}
		setPopupTitle(Registry.getRegistry(TCClassificationViewer.class).getString("g4mListValueButton.TITLE", "!!!List of Values"));
	}

	public void postUp() {
		String as[] = new String[1];
		as[0] = "Loading Values...";
		m_listPanel.getList().setListData(as);
		m_exceptionThrown = false;
		LoadValuesOperation loadvaluesoperation = new LoadValuesOperation();
		loadvaluesoperation.addOperationListener(this);
		getSession().queueOperation(loadvaluesoperation);
		super.postUp();
	}

	public void exceptionThrown(Exception exception) {
		final Exception e = exception;
		try {
			SwingUtilities.invokeLater(new Runnable() {

				public void run() {
					String as[] = new String[3];
					as[0] = "Loading Values...";
					as[1] = "Exception thrown";
					as[2] = e.toString();
					m_listPanel.getList().setListData(as);
					m_listPanel.getList().repaint();
					m_exceptionThrown = true;
				}
			});
		} catch (Exception exception1) {
			e.printStackTrace();
		}
	}

	public void startOperation(String s) {
	}

	public void endOperation() {
		try {
			SwingUtilities.invokeLater(new Runnable() {

				public void run() {
					if (!m_exceptionThrown)
						if (m_values != null) {
							setPopupTitle((new StringBuilder()).append(Registry.getRegistry(TCClassificationViewer.class).getString("g4mListValueButton.TITLE", "!!!List of Values")).append(" (").append(m_values.size()).append(")").toString());
							ICSAutoFilterValue aicsautofiltervalue[] = new ICSAutoFilterValue[m_values.size()];
							m_values.toArray(aicsautofiltervalue);
							m_listPanel.getList().setListData(aicsautofiltervalue);
							ICSFormat icsformat = aicspropertydescription.getFormat();
							if (icsformat.isReal() || icsformat.isInteger())
								m_listPanel.getList().setCellRenderer(new ListValueRenderer());
							if (icsformat.isList())
								m_listPanel.getList().setCellRenderer(new ListValueRenderer());
							m_listPanel.getList().repaint();
							m_listPanel.getList().validate();
						} else {
							String as[] = new String[1];
							as[0] = "No Values found!";
							m_listPanel.getList().setListData(as);
							m_listPanel.getList().repaint();
						}
				}
			});
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}

	private ValueListBox m_listPanel;
	private java.util.List m_values;
	private boolean m_exceptionThrown;
	private ImageIcon m_icon;
	private ImageIcon m_editIcon;
	private boolean m_refOnEdit;
	public static HashMap m_optStorageValuesMap;
	private static final Logger logger;

	static {
		logger = Logger.getLogger("com/teamcenter/rac/classification/common/form/G4MListValuesButton");
		if (Debug.isOn("G4M") && !logger.isDebugEnabled())
			logger.setLevel(Level.DEBUG);
	}
}
