package cn.net.connor.std.processedit.processview;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.pse.common.BOMLineNode;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.Registry;

@SuppressWarnings("serial")
public class ProcessPropertyEditor extends JPanel implements FocusListener {

	private PropertyPanel propPanel;
	private JButton b_save;
	private static final Registry REG = Registry.getRegistry(ProcessPropertyEditor.class);

	public void initUI() throws Exception {
		this.setLayout(new BorderLayout());
		this.propPanel = new PropertyPanel();
		JScrollPane propScroll = new JScrollPane(this.propPanel);
		propScroll.setBorder(BorderFactory.createEmptyBorder());
		this.add(BorderLayout.CENTER, propScroll);
		this.add(BorderLayout.SOUTH, initBtnPanel());
		propPanel.refreshUI(null);
		addListeners();
	}

	private void addListeners() {
		this.b_save.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						b_save.setEnabled(false);
						try {
							propPanel.save();
						} catch (Exception e) {
							e.printStackTrace();
							MessageBox.post(e);
						}
						b_save.setEnabled(true);
					}
				}).start();
			}
		});
	}

	private JPanel initBtnPanel() {
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 5));
		this.b_save = new JButton(REG.getString("save"));
		panel.add(b_save);
		return panel;
	}


	public synchronized void updateSelection(Object targetObj) {
		System.out.println("Update: "+targetObj);
		if (targetObj != null && targetObj instanceof AIFComponentContext) {
			targetObj = ((AIFComponentContext) targetObj).getComponent();
		}
		if (targetObj != null && targetObj instanceof BOMLineNode) {
			targetObj = ((BOMLineNode) targetObj).getComponent();
		}
		if (targetObj == null || !(targetObj instanceof TCComponentBOMLine)) {
		} else {
			TCComponentBOMLine targetLine = (TCComponentBOMLine) targetObj;
			b_save.setEnabled(false);
			try {
				if (propPanel.refreshUI(targetLine)) {
					b_save.setEnabled(true);
				}
			} catch (Exception e) {
				MessageBox.post(e);
				e.printStackTrace();
			}
		}
		propPanel.revalidate();
		propPanel.repaint();
	}

	@Override
	public void focusGained(FocusEvent e) {
		//this.currentComp = e.getSource();
	}

	@Override
	public void focusLost(FocusEvent e) {
	}

}