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

import java.awt.Component;
import java.net.URL;
import java.util.Enumeration;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import cn.com.origin.autocode.classification.ClassificationPropertyNames;
import cn.com.origin.autocode.newitem.generatcode.PackClassificationInfos;
import cn.com.origin.autocode.newitem.system.ORNewItemDialog;

import com.teamcenter.rac.aifrcp.AifrcpPlugin;
import com.teamcenter.rac.commands.newitem.NewItemDialog;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCClassificationService;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.ics.ICSApplicationObject;
import com.teamcenter.rac.kernel.ics.ICSHierarchyNodeDescriptor;
import com.teamcenter.rac.kernel.ics.ICSView;

public class CreateClassificationPanel {
	JScrollPane classificationPropertyPanel;
	CreateClassificationPropertyPanel createClassificationPropertyPanel;
	TCClassificationService classificationService;
	ICSApplicationObject icsapplicationobject;
	NewItemDialog newItemDialog;
	JTree tree;

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

	public CreateClassificationPanel(NewItemDialog newItemDialog) {
		classificationService = getSession().getClassificationService();
		this.newItemDialog = newItemDialog;
		try {
			icsapplicationobject = classificationService.newICSApplicationObject("ICM");
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	public JScrollPane createPropertyInfoPanel() {
		createClassificationPropertyPanel = new CreateClassificationPropertyPanel();
		classificationPropertyPanel = createClassificationPropertyPanel.getPropertyPanel();
		return classificationPropertyPanel;
	}

	public JScrollPane CreateRootClassificationInfoPanel(String rootID, String rootName, String type) {
		JScrollPane scrollPane = new JScrollPane();
		ClassificationTreeData rootTreeData = new ClassificationTreeData(rootID, rootName, type, null, null);
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(rootTreeData);

		DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
		tree = new JTree(treeModel);
		tree.addTreeSelectionListener(new treeSelectedListener());
		tree.setCellRenderer(new MyRenderer());
		tree.addTreeExpansionListener(new TreeExpandedListener());

		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollPane.getViewport().setView(tree);
		return scrollPane;
	}

	public void addClassificationInfoPanel(DefaultMutableTreeNode parentTreeNode, String rootID, String rootName, String type) {
		try {
			setChildrenNode(0, rootID, parentTreeNode, ((ClassificationTreeData) parentTreeNode.getUserObject()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}

	public JScrollPane CreateClassificationInfoPanel(String rootID, String rootName, String type) {
		// JPanel panel = new JPanel(new BorderLayout());
		// JScrollPane scrollPane = new JScrollPane(panel);
		JScrollPane scrollPane = new JScrollPane();
		try {
			ClassificationTreeData rootTreeData = new ClassificationTreeData(rootID, rootName, type, null, null);
			DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(rootTreeData);
			setChildrenNode(0, rootID, rootNode, rootTreeData);

			DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
			JTree tree = new JTree(treeModel);
			tree.addTreeSelectionListener(new treeSelectedListener());
			tree.setCellRenderer(new MyRenderer());
			tree.addTreeExpansionListener(new TreeExpandedListener());

			scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
			scrollPane.getViewport().setView(tree);
			// panel.add(scrollPane, BorderLayout.CENTER);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return scrollPane;
	}

	private class MyRenderer extends DefaultTreeCellRenderer {
		private static final long serialVersionUID = 1L;
		ImageIcon imageIcon;

		public MyRenderer() {

		}

		public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
			super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
			DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) value;
			ClassificationTreeData treeData = (ClassificationTreeData) treeNode.getUserObject();
			this.setText(treeData.getName());
			String type = treeData.getType();
			URL url = null;
			if (type.equals(ClassificationPropertyNames.icsGroupType)) {
				url = this.getClass().getResource("images/inclassgroup_16.png");
			} else if (type.equals(ClassificationPropertyNames.icsAbstractType)) {
				url = this.getClass().getResource("images/inclassabstractclass_16.png");
			} else if (type.equals(ClassificationPropertyNames.icsInstanceType)) {
				url = this.getClass().getResource("images/inclassstorageclass_16.png");
			}
			if (url != null) {
				imageIcon = new ImageIcon(url);
				setIcon(imageIcon);
			}
			return this;
		}
	}

	private void setChildrenNode(int expandNum, String parentIcsID, DefaultMutableTreeNode parentNode, ClassificationTreeData parentClassificationTreeData) {
		if (expandNum > 1) {
			return;
		}
		if ((parentNode.children() != null) && (parentNode.children().hasMoreElements())) {
			expandNum++;
			Enumeration childrensNode = parentNode.children();
			while (childrensNode.hasMoreElements()) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) childrensNode.nextElement();
				ClassificationTreeData treeData = (ClassificationTreeData) node.getUserObject();
				setChildrenNode(expandNum, treeData.getId(), node, treeData);
			}
			return;
		}
		parentClassificationTreeData.setChildrenTreeNodes(null);
		ICSHierarchyNodeDescriptor[] icsnode = classificationService.getChildren(parentIcsID, false, true, 0, 0);
		if (icsnode != null) {
			expandNum++;
			for (int i = 0; i < icsnode.length; i++) {
				String node_id = icsnode[i].getId();
				String node_name = icsnode[i].getName();
				String type = icsnode[i].getType();
				if (icsnode[i].isStorageClass()) {
					type = ClassificationPropertyNames.icsInstanceType;
				}
				ClassificationTreeData classificationTreeData = new ClassificationTreeData(node_id, node_name, type, parentClassificationTreeData, null);
				parentClassificationTreeData.addChildrenTreeNodes(classificationTreeData);
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(classificationTreeData);
				parentNode.add(node);

				setChildrenNode(expandNum, node_id, node, classificationTreeData);
			}
		}
	}

	private class TreeExpandedListener implements TreeExpansionListener {
		public void treeCollapsed(TreeExpansionEvent treeexpansionevent) {
		}

		public void treeExpanded(TreeExpansionEvent treeexpansionevent) {
			// JTree tree = (JTree) treeexpansionevent.getSource();
			// TreePath expandPath = treeexpansionevent.getPath();
			// if (expandPath == null) {
			// return;
			// }
			// DefaultMutableTreeNode expanddNode = (DefaultMutableTreeNode)
			// expandPath.getLastPathComponent();
			// if (expanddNode == null) {
			// return;
			// }
			// ClassificationTreeData treeData = (ClassificationTreeData)
			// expanddNode.getUserObject();
			// Enumeration childrens = expanddNode.children();
			// TreeNode[] treeNodes= expanddNode.getPath();
			// while (childrens.hasMoreElements()) {
			// System.out.println("childrens.nextElement()==============" +
			// childrens.nextElement());
			// DefaultMutableTreeNode childrenNode = (DefaultMutableTreeNode)
			// childrens.nextElement();
			// ClassificationTreeData childrenData = (ClassificationTreeData)
			// childrenNode.getUserObject();
			// setChildrenNode(0, childrenData.getId(), childrenNode,
			// childrenData);
			// }
			// JTree tree = (JTree) treeexpansionevent.getSource();
			try {
				TreePath selectedPath = treeexpansionevent.getPath();
				if (selectedPath == null) {
					return;
				}
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
				if (selectedNode == null) {
					return;
				}
				ClassificationTreeData treeData = (ClassificationTreeData) selectedNode.getUserObject();

				if (treeData.getId().equals("ICM")) {
					addClassificationInfoPanel(selectedNode, treeData.getId(), treeData.getName(), ClassificationPropertyNames.icsGroupType);
					return;
				} else {
					setChildrenNode(0, treeData.getId(), selectedNode, treeData);
				}
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						tree.repaint();
						tree.updateUI();
					}
				});

				// createClassificationPropertyPanel.createPropertyPanel(treeData.getName(), treeData.getId());
				//
				// PackClassificationInfos classificationInfos = new PackClassificationInfos();
				// String icsID = treeData.getId();
				// if ((icsID != null) && (!icsID.equals(""))) {
				// TCClassificationService classificationService = newItemDialog.session.getClassificationService();
				// ICSApplicationObject icsapplicationobject = classificationService.newICSApplicationObject("ICM");
				// icsapplicationobject.setView("Base", icsID);
				// ICSView icsview = icsapplicationobject.getView();
				// if (icsview.isClassAbstract()) {
				// icsID = "Abstract";
				// }
				// }
				//
				// classificationInfos.setIcsID(icsID);
				// classificationInfos.setPropertyMaps(createClassificationPropertyPanel.getPropertyInfos());
				// if (newItemDialog instanceof ORNewItemDialog) {
				// ORNewItemDialog orNewItemDialog = (ORNewItemDialog) newItemDialog;
				// orNewItemDialog.setClassificationInfos(classificationInfos);
				// orNewItemDialog.setNotNullClassificationPropTextField(createClassificationPropertyPanel.getNotNullClassificationPropTextField());
				// orNewItemDialog.setClassificationService(createClassificationPropertyPanel.getClassificationService());
				// orNewItemDialog.setIcsView(createClassificationPropertyPanel.getICSView());
				// orNewItemDialog.setIcsapplicationobject(createClassificationPropertyPanel.getICSApplicationObject());
				// }
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private class treeSelectedListener implements TreeSelectionListener {
		public void valueChanged(TreeSelectionEvent tse) {
			try {

				TreePath selectedPath = tse.getNewLeadSelectionPath();
				JTree tree = (JTree) tse.getSource();

				if (selectedPath == null) {
					return;
				}
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
				if (selectedNode == null) {
					return;
				}
				ClassificationTreeData treeData = (ClassificationTreeData) selectedNode.getUserObject();

				if (treeData.getId().equals("ICM")) {
					addClassificationInfoPanel(selectedNode, treeData.getId(), treeData.getName(), ClassificationPropertyNames.icsGroupType);
					return;
				}
				// else {
				// setChildrenNode(0, treeData.getId(), selectedNode, treeData);
				// }

				createClassificationPropertyPanel.createPropertyPanel(treeData.getName(), treeData.getId(), newItemDialog);

				PackClassificationInfos classificationInfos = new PackClassificationInfos();
				String icsID = treeData.getId();
				if ((icsID != null) && (!icsID.equals(""))) {
					TCClassificationService classificationService = newItemDialog.getSession().getClassificationService();
					ICSApplicationObject icsapplicationobject = classificationService.newICSApplicationObject("ICM");
					icsapplicationobject.setView("Base", icsID);
					ICSView icsview = icsapplicationobject.getView();
					if (icsview.isAbstract()) {
						icsID = "Abstract";
					}
				}

				classificationInfos.setIcsID(icsID);
				classificationInfos.setPropertyMaps(createClassificationPropertyPanel.getPropertyInfos());
				classificationInfos.setICSPropertyDescription(createClassificationPropertyPanel.getICSPropertyDescriptions());
				classificationInfos.setIcsPropList(createClassificationPropertyPanel.getIcsPropList());
				if (newItemDialog instanceof ORNewItemDialog) {
					ORNewItemDialog orNewItemDialog = (ORNewItemDialog) newItemDialog;
					orNewItemDialog.setClassificationInfos(classificationInfos);
					orNewItemDialog.setNotNullClassificationPropTextField(createClassificationPropertyPanel.getNotNullClassificationPropTextField());
					orNewItemDialog.setClassificationService(createClassificationPropertyPanel.getClassificationService());
					orNewItemDialog.setIcsView(createClassificationPropertyPanel.getICSView());
					orNewItemDialog.setIcsapplicationobject(createClassificationPropertyPanel.getICSApplicationObject());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}