package de.dass_it.vanhelsing.gui;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.swing.tree.DefaultMutableTreeNode;

import de.dass_it.vanhelsing.gui.items.ConcreteUserObjectItem;
import de.dass_it.vanhelsing.gui.items.UserObjectItemType;
import de.dass_it.www.vanhelsing.VanHelsingStub.ResourceInfo;

/**
 * List all Bacula configuration components by name.
 */
public class ConfigurationBean implements IViewBean{
	
	
	private DataTree dataTree;
	private ConcreteUserObjectItem selectedObject;
	private boolean createResource;
	//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 parent;
		ResourceInfo resItems[];
		SimpleResource sr;
		Client c = new Client();
		UserObjectItemFactory UOFactory = new UserObjectItemFactory();
		setDataTree(new DataTree());
		dataTree.setTree("Configuration");
		for (String name : BeanUtil.getProperty("nodes").split(",")){
			parent = dataTree.createNode(dataTree.getRoot(), 
					UOFactory.createUserObjectItem(
							c.makeResourceInfo(BeanUtil.getProperty("defaultdirector"), -1, name, name)
					)
			);
			resItems = c.getListResources(BeanUtil.getProperty("defaultdirector"), name);
			if (resItems != null){
				for (ResourceInfo rinfo : resItems){
					sr = c.getSimpleResource(rinfo.getDirector(), rinfo.getResId());
					if (sr != null){
						//TODO: discard the SimpleResource ResInfo return value and work with the query object
						dataTree.createNode(parent, 
								UOFactory.createUserObjectItem(
										sr.getResourceAttributeType(), rinfo));
					}
				}
			}
		}
		dataTree.createKeyValueLists();
		dataTree.updateUserObjects();
		createResource = false;
		selectedObject = null;
	}
	
	/**
	 * 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 renderResource(ActionEvent ae){
		DefaultMutableTreeNode node;
		String id = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userObject.resId");
		int numId = new Integer(id);
		String name = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userObject.resName");
		if (numId > 0){
			node = dataTree.getNodeById(numId);
			selectedObject = (ConcreteUserObjectItem)((UserObjectItemType)(node.getUserObject())).getUserObject();
		} else {
			node = dataTree.getNodeByName(name);
			selectedObject = (ConcreteUserObjectItem)((UserObjectItemType)(node.getUserObject())).getUserObject();
		}
		createResource = false;
	}

	/**
	 * reads the properties of a given resource to create a resource object
	 * @param ae
	 */
	public void newResourceButtonListener(ActionEvent ae){
		String type = "Client";
		UserObjectItemFactory UOFactory = new UserObjectItemFactory();
		selectedObject = (ConcreteUserObjectItem)UOFactory.createUserObjectItem(type);
		for (ViewItem vi : selectedObject.getViewItemList()){
			if(vi.getSelectOneMenu()){
				vi.setKeyValueList(dataTree.getKeyValueList().get(vi.getKey()));
			}
			if (vi.getRadioGroup()){
				vi.setKeyValueList(dataTree.getKeyValueList().get("trueFalse"));
			}
		}
		createResource = true;
	}

	public void newClientButtonListener(ActionEvent ae){
		newResourceButtonListener(ae);
	}
	public void userObjectItemOptionSelected(ValueChangeEvent vce){
		System.err.println("vce.oldValue: " +vce.getOldValue()+" vce.newValue: "+vce.getNewValue());
		
	}
	/**
	 * 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.");
	}
	/**
	 * save the currently selected object
	 * @param ae
	 */
	public void saveClientButtonListener(ActionEvent ae){
		if (createResource){
			Client c = new Client();
			SimpleResource sr;
			UserObjectItemFactory UOFactory = new UserObjectItemFactory();
			for (ViewItem vi : selectedObject.getViewItemList()){
				if(vi.getKey().equals("name")){
					selectedObject.setResName(vi.getKeyValue());
				}
			}
			int newResId = 
				c.createSimpleResource(c.makeResAttrTypeArray(selectedObject.getViewItemList()),
					c.makeResourceInfo(selectedObject.getDirector(), selectedObject.getResId(),
							selectedObject.getResName(), selectedObject.getResType()));
			BeanUtil.setInfoMessage(null, "Neue Resource erzeugt (Id: "+newResId+")");
			//neue Resource einlesen und in den Baum eintragen
			//sr = c.getSimpleResource(selectedObject.getDirector(), newResId);
			sr = new SimpleResource();
			sr.setResourceAttributeType(c.makeResAttrTypeArray(selectedObject.getViewItemList()));
			sr.setResourceInfo(c.makeResourceInfo(selectedObject.getDirector(), selectedObject.getResId(),
					selectedObject.getResName(), selectedObject.getResType()));
			dataTree.createNode(dataTree.getNodeByName("Client"),
					UOFactory.createUserObjectItem(sr.getResourceAttributeType(),
							sr.getResourceInfo()));
			dataTree.updateUserObjects();
		}
	}

	/**
	 * Setter method for the tree attribute
	 * @param tree	tree contains the DefaultTreeModel for the data tree
	 */
	public void setDataTree(DataTree dataTree) {
		this.dataTree = dataTree;
	}
	/**
	 * getter method for the tree attribute
	 * @return tree		tree contains the DefaultTreeModel for the data tree
	 */
	public DataTree getDataTree() {
		return dataTree;
	}

	public void createNodeButtonListener(ActionEvent ae) {
		// TODO Auto-generated method stub
		
	}

	public void deleteNodeButtonListener(ActionEvent ae) {
		// TODO Auto-generated method stub
		
	}


	public void readNodeButtonListener(ActionEvent ae) {
		// TODO Auto-generated method stub
		
	}

	public void selectNode(ActionEvent ae) {
		// TODO Auto-generated method stub
		
	}

	public void updateNodeButtonListener(ActionEvent ae) {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * gettter method for the selectedObject attribute
	 * @return selectedObject	selectedObject contains the data object of the selected leaf node.
	 */
	public ConcreteUserObjectItem getSelectedObject() {
		return selectedObject;
	}
	
	/**
	 * setter method for the selectedObject attribute
	 * @param selectedObject	selectedObject contains the data object of the selected leaf node
	 */
	public void setSelectedObject(ConcreteUserObjectItem 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){
				return selectedObject.getResId();
			}
		return -1;
	}
	/*public String getSelectedName(){
		if (selectedObject != null){
			if (selectedObject.size() > 0){
				return selectedObject.get(0).getResName();
			}
		}
		return "";
	}*/
	public void setCreateResource(boolean b){
		this.createResource = b;
	}
	public boolean getCreateResource(){
		return createResource;
	}

}
