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

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.TreeCellRenderer;

import cn.net.connor.std.processedit.processview.safeicon.SafeIconBean;

@SuppressWarnings("serial")
public class CheckBoxTreeCellRenderer extends JPanel implements TreeCellRenderer {
	protected JCheckBox check;
	protected CheckBoxTreeLabel label;
	private JLabel iconLabel;

	public CheckBoxTreeCellRenderer() {
		setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
		add(check = new JCheckBox());
		add(label = new CheckBoxTreeLabel());
		add(iconLabel = new JLabel(""));
		check.setBackground(UIManager.getColor("Tree.textBackground"));
		label.setForeground(UIManager.getColor("Tree.textForeground"));
		iconLabel.setForeground(UIManager.getColor("Tree.textForeground"));
	}

	@Override
	public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
		String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
		setEnabled(tree.isEnabled());
		check.setSelected(((CheckBoxTreeNode) value).isSelected());
		label.setFont(tree.getFont());
		label.setText(stringValue);
		label.setSelected(selected);
		label.setFocus(hasFocus);
		if(value!=null&&(value instanceof CheckBoxTreeNode)) {
			Object bean = ((CheckBoxTreeNode)value).getUserObject();
			if(bean!=null && (bean instanceof SafeIconBean)) {
				iconLabel.setIcon(((SafeIconBean)bean).getIcon());
				iconLabel.revalidate();
			}
		}
		return this;
	}

	@Override
	public Dimension getPreferredSize() {
		Dimension dCheck = check.getPreferredSize();
		Dimension dLabel = label.getPreferredSize();
		Dimension dIcon = iconLabel.getPreferredSize();
		return new Dimension(dCheck.width + dLabel.width+ dIcon.width+130, dCheck.height < dLabel.height ? dLabel.height : dCheck.height + 20);
	}

	@Override
	public void doLayout() {
		super.doLayout();
//		Dimension dCheck = check.getPreferredSize();
//		Dimension dLabel = label.getPreferredSize();
//		int yCheck = 0;
//		int yLabel = 0;
//		if (dCheck.height < dLabel.height)
//			yCheck = (dLabel.height - dCheck.height) / 2;
//		else
//			yLabel = (dCheck.height - dLabel.height) / 2;
//		check.setLocation(0, yCheck);
//		check.setBounds(0, yCheck, dCheck.width, dCheck.height-2);
//		label.setLocation(dCheck.width, yLabel);
//		label.setBounds(dCheck.width, yLabel, dLabel.width, dLabel.height-3);
//		iconLabel.setLocation(dCheck.width+dLabel.width, yLabel);
	}

	@Override
	public void setBackground(Color color) {
		if (color instanceof ColorUIResource)
			color = null;
		super.setBackground(color);
	}
}