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

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentFolder;

import cn.net.connor.std.aifrcp.util.KUtil;

public class SafeIconBean {

	private List<SafeIconBean> children;
	private TCComponentDataset iconDataset;
	private String nodeName;
	private ImageIcon icon;

	private SafeIconBean(List<SafeIconBean> children, TCComponentDataset iconDataset, String nodeName, ImageIcon icon) {
		super();
		this.children = children;
		this.iconDataset = iconDataset;
		this.nodeName = nodeName;
		this.icon = icon;
	}

	public List<SafeIconBean> getChildren() {
		return children;
	}

	public TCComponentDataset getIconDataset() {
		return iconDataset;
	}

	public String getNodeName() {
		return nodeName;
	}

	public ImageIcon getIcon() {
		return icon;
	}

	@Override
	public String toString() {
		return nodeName;
	}

	public static SafeIconBean parse(TCComponent comp, List<String> dsTypes) throws Exception {
		if (comp == null) {
			return null;
		}
		List<SafeIconBean> children = new ArrayList<>();
		TCComponentDataset iconDataset = null;
		ImageIcon icon = null;
		String nodeName = comp.getStringProperty("object_name");
		if (comp instanceof TCComponentFolder) {
			AIFComponentContext[] cc = comp.getChildren();
			int len = KUtil.getLen(cc);
			for (int i = 0; i < len; i++) {
				TCComponent child = (TCComponent) cc[i].getComponent();
				SafeIconBean childNode = SafeIconBean.parse(child, dsTypes);
				if (childNode != null) {
					children.add(childNode);
				}
			}
		} else if (comp instanceof TCComponentDataset) {
			iconDataset = (TCComponentDataset) comp;
			String dstype = iconDataset.getType();
			System.out.println(">> find dataset: " + iconDataset + "[" + dstype + "]");
			if (dsTypes.contains(dstype)) {
				File iconFile = KUtil.getDatasetFile(iconDataset);
				FileInputStream in = new FileInputStream(iconFile);
				Image image = ImageIO.read(in);
				in.close();
				//icon = new ImageIcon(iconFile.getAbsolutePath());
				icon = new ImageIcon(image.getScaledInstance(20, 20, Image.SCALE_DEFAULT));
				iconFile.delete();
			} else {
				System.out.println(">> skip");
			}
		}
		if (icon == null && children.size() == 0) {
			return null;
		}
		return new SafeIconBean(children, iconDataset, nodeName, icon);
	}

	public Object[] getRowData(int index) {
		return new Object[] {index, this, icon};
	}
}
