package net.sf.anpr.rcp.filesystem;

import java.awt.Color;
import java.awt.Component;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.UIManager;

class TreeCellRenderer implements javax.swing.tree.TreeCellRenderer {
	FastLabel fastlabel = new FastLabel(false);
	Icon drive = null;
	Icon document = null;
	Icon folder = null;
	Icon folder_closed = null;

	FileView fv = null;

	FileFilter filter = null;

	public TreeCellRenderer() {
		try {
			this.drive = new ImageIcon(getClass().getResource("diskdrive.png"));
			this.document = new ImageIcon(getClass()
					.getResource("document.png"));
			this.folder = new ImageIcon(getClass().getResource("folder.png"));
			this.folder_closed = new ImageIcon(getClass().getResource(
					"folder_closed.png"));
		} catch (Throwable th) {
			System.err.println("Can't init icons ? : " + th.getMessage());
		}
	}

	void setFileView(FileView fv) {
		this.fv = fv;
	}

	void setFileFilter(FileFilter filter) {
		this.filter = filter;
	}

	public Component getTreeCellRendererComponent(JTree tree, Object value,
			boolean selected, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {
		if ((value instanceof FileTreeNode)) {
			FileTreeNode node = (FileTreeNode) value;

			Icon icon = null;

			if (node.root) {
				icon = this.drive;
			} else if (node.getFile() != null) {
				if (node.getFile().isDirectory())
					icon = !expanded ? this.folder_closed : this.folder;
				else {
					icon = this.document;
				}
			}

			if ((this.fv != null) && (!node.isRoot())) {
				Icon iconTmp = this.fv.getIcon(node.getFile());
				if (iconTmp != null) {
					icon = iconTmp;
				}
			}

			this.fastlabel.setIcon(icon);

			this.fastlabel.setText(node.toString());

			if (selected) {
				this.fastlabel.setForeground(UIManager
						.getColor("List.selectionForeground"));
				this.fastlabel.setBackground(UIManager
						.getColor("List.selectionBackground"));
			} else {
				Color foreground = tree.getForeground();
				Color background = tree.getBackground();

				if ((this.fv != null) && (!node.isRoot())) {
					Color tmp = this.fv.getForeground(node.getFile());
					if (tmp != null)
						foreground = tmp;
					tmp = this.fv.getBackground(node.getFile());
					if (tmp != null) {
						background = tmp;
					}
				}

				if ((this.filter != null) && (!node.isRoot())
						&& (!this.filter.accept(node.getFile()))) {
					foreground = background.darker().darker();
				}

				this.fastlabel.setForeground(foreground);
				this.fastlabel.setBackground(background);
			}

			return this.fastlabel;
		}
		return this.fastlabel;
	}
}