package de.dass_it.vanhelsing.gui;

import java.lang.reflect.Method;
import java.util.ArrayList;

import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import de.dass_it.vanhelsing.gui.items.*;
import de.dass_it.www.vanhelsing.*;
import de.dass_it.www.vanhelsing.VanHelsingCallbackHandler.*;
import de.dass_it.www.vanhelsing.VanHelsingStub.*;

/**
 * List all Bacula configuration components by name.
 */
public class ConfigurationBean extends TreeNavigation {

	private DefaultTreeModel tree;
	private ArrayList<ViewItem> selectedObject;
	private String selectedId;

	public ConfigurationBean() {
		init();
	}
	
	/**
	 * init() builds the data tree of the configuration view. The heading nodes are read from the properties file.
	 * the web service will be queried for each heading node(e.g. client).
	 */
	private void init(){
		DefaultMutableTreeNode root = new DefaultMutableTreeNode();
		DefaultMutableTreeNode header;
		DefaultMutableTreeNode leaf;
		String type;
		ListResourcesType lrt;
		GetResourceType grt;
		DefaultMutableTreeNode myNode;
		ResourceInfo[] ri;
		SimpleResource sr;

		Client c = new Client();
		setTree(super.createTree(root, BeanUtil.getProperty("nodes").split(","), "Configuration"));

		
		for (int i = 0; i < tree.getChildCount(root); i++) {
			header = (DefaultMutableTreeNode) tree.getChild(root, i);
			type = ((UserObjectItemType) header.getUserObject())
					.getUserObject().getResType();
			lrt = new ListResourcesType();
			lrt.setDirector("bacula-dir");
			lrt.setResourceType(type);
			ri = c.getListResources(lrt);
			if (ri == null || ri.length == 0)
				continue;
			for (int j = 0; j < ri.length; j++) {
				myNode = addNode(header, type, ri[j]);
				grt = new GetResourceType();
				grt.setDirector(lrt.getDirector());
				grt.setResId(ri[j].getResId());
				sr = c.getSimpleResource(grt);
				myNode = addNode(myNode, type, sr.getResourceAttributeType());
				if (myNode != null) {
					header.add(myNode);
				}
			}
		} 
	}

	/**
	 * transfers the selected (by attribute resId) dataobject (resource) into an ArrayList of ViewItems.<br/>
	 * Each ViewItem contain the key value pair and the rendering type. If the attribute is rendered as a
	 * selectOneMenu, the values for the selectOneMenu will be read from the data tree.
	 * 
	 * @param ae	ActionEvent which contains relevant information about the component tree. the variable is not used.
	 */
	public void userObjectItemNodeSelected(ActionEvent ae) {
		DefaultMutableTreeNode node;
		UserObjectItem userObject;
		selectedObject = new ArrayList<ViewItem>();
		String Id = BeanUtil.getRequestParameter("userObject.resId");
		String selected = BeanUtil.getRequestParameter("ice.event.shift");
		node = getNode(Id, tree);
		if (selected.equals("true")){
			((UserObjectItemType)node.getUserObject()).switchSelected();
		}
		String type = ((UserObjectItem) ((UserObjectItemType) node
				.getUserObject()).getUserObject()).getResType();
		String resName = ((ItemType)((UserObjectItem) ((UserObjectItemType) node
				.getUserObject()).getUserObject())).getResName();
		String director = ((ItemType)((UserObjectItem) ((UserObjectItemType) node
				.getUserObject()).getUserObject())).getDirector();
		String classType = "de.dass_it.vanhelsing.gui.items." + type + "Item";
		String accessType = BeanUtil.getAccessType(type.toLowerCase());
		try {
			UserObjectItem item = ((UserObjectItemType) (node.getUserObject()))
					.getUserObject();
			Class c = ((UserObjectItemType) (node.getUserObject()))
					.getUserObject().getClass();
			Method[] m = c.getDeclaredMethods();
			String keyValue;
			String key;
			ViewItem vi;
			for (Method n : m) {
				if (n.getName().startsWith("get")) {
					keyValue = (String) n.invoke(item, (Object[]) null);
					if (keyValue == null)
						continue;
					key = n.getName().substring(3);
					vi = new ViewItem();
					vi.setResId(new Integer(Id));
					vi.setKey(key);
					vi.setKeyValue(keyValue);
					vi.setResType(type);
					vi.setResName(resName);
					vi.setDirector(director);
					vi.setRendererFlag(BeanUtil.getRenderer(accessType, key));
					vi.setRequired(BeanUtil.getRequired(accessType, key));
					if (vi.getSelectOneMenu() != null){
						DefaultMutableTreeNode[] dmtn = getChildNodes(tree, vi.getKey());
						if (dmtn != null) {
							SelectItem[] si = new SelectItem[dmtn.length];
							String objectType;
							for (int i = 0; i < dmtn.length; i++){
								UserObjectItem nodeObject = ((UserObjectItemType)dmtn[i].getUserObject()).getUserObject();
								objectType = "de.dass_it.vanhelsing.gui.items." + vi.getKey() +"Item";
								Class subClass = Class.forName(objectType);
								Class myClass = nodeObject.getClass().asSubclass(subClass);
								Method o = myClass.getMethod("getName", (Class[])null);
								si[i] = new SelectItem((String)o.invoke(nodeObject, (Object[])null),
										(String)o.invoke(nodeObject, (Object[])null));
								
							}
							vi.setKeyValueList(si);
						}
					}
					selectedObject.add(vi);
				}
				selectedObject.trimToSize();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * return an array of nodes of a given resource type
	 * 
	 * @param tree2		copy of the data tree
	 * @param key		name of the requested resource type
	 * @return dmtn		array of nodes of a given resource type
	 * @return null		null object there are no nodes of the requested type
	 */
	private DefaultMutableTreeNode[] getChildNodes(DefaultTreeModel tree2, String key) {
		DefaultMutableTreeNode[] dmtn;
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree2.getRoot();
		DefaultMutableTreeNode node;
		for (int i = 0; i< root.getChildCount(); i++){
			node = (DefaultMutableTreeNode)root.getChildAt(i);
			if (((UserObjectItemType)(node.getUserObject())).getUserObject().getResType().equals(key)){
				dmtn = new DefaultMutableTreeNode[node.getChildCount()];
				for (int j = 0; j < node.getChildCount(); j++){
					dmtn[j] = (DefaultMutableTreeNode)node.getChildAt(j);
				}
				return dmtn;
			}
		}
		return null;
	}
	/**
	 * 
	 * @param ae
	 */
	public void newResourceButtonListener(ActionEvent ae){
		DefaultMutableTreeNode node;
		UserObjectItem userObject;
		selectedObject = new ArrayList<ViewItem>();
		String Id = BeanUtil.getRequestParameter("userObject.ResId");
		String shift = BeanUtil.getRequestParameter("ice.event.shift");
		System.err.println(shift);
		if (Id == null){
			return;
		}
		node = getNode(Id, tree);
		String type = ((UserObjectItem) ((UserObjectItemType) node
				.getUserObject()).getUserObject()).getResType();
		ViewItem vi;
		String[] val;
		try{
			String type2 = "de.dass_it.vanhelsing.gui.items." +  type + "Item";
			Class newClass = Class.forName(type2);
			for (Method m : newClass.getDeclaredMethods()){
				if (m.getName().startsWith("get")) {
					vi = new ViewItem();
					vi.setKey(m.getName().substring(3));
					vi.setRendererFlag(BeanUtil.getRenderer(type, vi.getKey()));
					if (vi.getSelectOneMenu() != null){
						DefaultMutableTreeNode[] dmtn = getChildNodes(tree, vi.getKey());
						if (dmtn != null) {
							SelectItem[] si = new SelectItem[dmtn.length];
							String objectType;
							for (int i = 0; i < dmtn.length; i++){
								UserObjectItem nodeObject = ((UserObjectItemType)dmtn[i].getUserObject()).getUserObject();
								objectType = "de.dass_it.vanhelsing.gui.items." + vi.getKey() +"Item";
								Class subClass = Class.forName(objectType);
								Class myClass = nodeObject.getClass().asSubclass(subClass);
								Method o = myClass.getMethod("getName", (Class[])null);
								si[i] = new SelectItem((String)o.invoke(nodeObject, (Object[])null),
										(String)o.invoke(nodeObject, (Object[])null));
								
							}
							vi.setKeyValueList(si);
						}
					}
					if (vi.getInputText() != null){
						vi.setValue(BeanUtil.getProperty("director."+type+"."+vi.getKey()+".def"));
					}
				}
			}
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}
	/**
	 * **EXPERIMENTAL** returns type of the selected resource.
	 * The method is used for an evaluation about dynamic navigation.
	 * @param ae	ActionEvent contains relevant information about the jsf component tree.
	 * @return viewName	name of the resource type of the selected data tree node	
	 */
	public String newResourceListener(ActionEvent ae){
		if (selectedObject != null && selectedObject.size() > 0){
			String resType = selectedObject.get(0).getResType();
			String viewName = BeanUtil.getAccessType(resType);
			return viewName;
		}
		return "";
	}
	
	public void userObjectItemOptionSelected(ValueChangeEvent vce){
		
	}
	/**
	 * repeat the entire construction process of the data tree
	 * @param ae
	 */
	public void reloadResourceButtonListener(ActionEvent ae){
		init();
	}
	public void deleteResourceButtonListener(ActionEvent ae){
		BeanUtil.setInfoMessage(null, "Diese Methode ist noch nicht implementiert.");
	}
	/**
	 * **EXPERIMENTAL** writes the selected resource to the data tree of the web service.
	 * 
	 * @param ae	ActionEvent contains relevant information 
	 */
	public void saveButtonListener(ActionEvent ae) {
		if (selectedObject == null){
			BeanUtil.setInfoMessage(null, "bitte eine Resource zum Ändern auswählen");
		} else {
			Client c = new Client();
			ResourceInfo ri = new ResourceInfo();
			SetSimpleResourceResponse s2r2;
			ri.setDirector( selectedObject.get(0).getDirector() );
			ri.setResId( selectedObject.get(0).getResId() );
			ri.setResName( selectedObject.get(0).getResName() );
			ri.setResType( selectedObject.get(0).getResType() );
			// ResourceAttribute
			String key, value;
			ResourceAttributeType[] ra = new ResourceAttributeType[selectedObject.size()];
			for (int i = 0; i < selectedObject.size(); i++) {
				key = selectedObject.get(i).getKey();
				value = selectedObject.get(i).getKeyValue();
				ra[i] = new ResourceAttributeType();
				ra[i].setKey(key);
				ra[i].setValue(value);
			}
			ResourceInitialization rinit = new ResourceInitialization();
			rinit.setResInfo(ri);
			rinit.setResAttribute(ra);
			rinit.setReplace(true);
			s2r2 = c.setSimpleResource(rinit);
			System.err.println("Status setSimpleRes: "+s2r2.getStatus());
			BeanUtil.setErrorMessage(null, "Status setSimpleRessource: "+s2r2.getStatus());
			
			/*String status = s2r2.getStatus();
			if (selectedObject.get(0) != null){
				selectedObject.get(0).setResId(s2r2.getResId());
			}*/
			// TODO: write ResId to selectedObject
			// selectedObject.get(0).setResId(grt.getResId());
			// valueChangeEffect.setFired(false);
		}
	}
	/**
	 * Setter method for the tree attribute
	 * @param tree	tree contains the DefaultTreeModel for the data tree
	 */
	public void setTree(DefaultTreeModel tree) {
		this.tree = tree;
	}
	/**
	 * getter method for the tree attribute
	 * @return tree		tree contains the DefaultTreeModel for the data tree
	 */
	public DefaultTreeModel getTree() {
		return tree;
	}
	
	/**
	 * gettter method for the selectedObject attribute
	 * @return selectedObject	selectedObject contains the data object of the selected leaf node.
	 */
	public ArrayList<ViewItem> getSelectedObject() {
		return selectedObject;
	}
	
	/**
	 * setter method for the selectedObject attribute
	 * @param selectedObject	selectedObject contains the data object of the selected leaf node
	 */
	public void setSelectedObject(ArrayList<ViewItem> selectedObject) {
		this.selectedObject = selectedObject;
	}
	
	/**
	 * getter method for the resId attribute of the selectedObject i.e. the selected leaf node of the data tree
	 * @return id	resId attribute of the selected object
	 */
	public int getSelectedId(){
		if (selectedObject != null){
			if (selectedObject.size() > 0){
				return selectedObject.get(0).getResId();
			}
		}
		return -1;
	}

}
