/* $Id: ReasoningWebDesktop.java 373 2011-10-01 16:30:41Z shayashi $ */
package smart_gs.reasoning_web.desktop.swingui;


import java.util.Calendar;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import smart_gs.logical.StandardTextDocument;
import smart_gs.reasoning_web.RootFolder;
import smart_gs.reasoning_web.desktop.logical.DeskTopFolder;
import smart_gs.reasoning_web.desktop.logical.ShortCut;
import smart_gs.reasoning_web.logical.GS_RWElement;
import smart_gs.reasoning_web.swingui.ReasoningWebFrame;

@SuppressWarnings("serial")
public class ReasoningWebDesktop{
	
	private static ReasoningWebDesktop singleton = new ReasoningWebDesktop();
	
	private ReasoningWebDesktop() {
		ReasoningWebFrame.getInstance();
	}
	public DeskTopFolder getRootFolder(){
		return RootFolder.getInstance();
	}
	public DeskTopFolder getFolder(String name){
		
		return this.getRootFolder().getFolder(name);
	}
	public void addQueryHistory(GS_RWElement query){
		Calendar calendar = Calendar.getInstance();
		String name =""+calendar.getTime();
		String source ="<xml><time>"+name+"</time></xml>";
		if(!this.getRootFolder().hasFolder("queries")){
			this.getRootFolder().add(new DeskTopFolder(this.getRootFolder(),"queries"));
		}
		StandardTextDocument memo = new StandardTextDocument();
		memo.setSource(source);
		this.getRootFolder().getFolder("queries").add(new ShortCut(query,name,memo));
		ReasoningWebFrame.getInstance().getDesktopPanel().updateAll();
	}
	
	public void addResource(GS_RWElement resource,String name,StandardTextDocument memo){
		ShortCut shortcut = new ShortCut(resource,name,memo);
		ReasoningWebFrame.getInstance().getCurrentFolder().add(shortcut);
		ReasoningWebFrame.getInstance().getDesktopPanel().updateAll();
	}
	public static ReasoningWebDesktop getInstance(){
		return singleton;
	}
	public void save(Document document,Element parent){
		Element element = document.createElement("desktop");
		element.appendChild(RootFolder.getInstance().createXMLElement(document));
		
		parent.appendChild(element);
	}

	public void restore(Element desktopElement) {
		NodeList list = desktopElement.getElementsByTagName("desktopFolder");
	
		Element rootElement = null;
		for(int i=0;i<list.getLength();i++){
			Element e = (Element)list.item(i);
			if(e.hasAttribute("isRoot")){
				rootElement = (Element)list.item(i);
			}
		}
		
		if(rootElement == null){
			return;
		}
		
		RootFolder.getInstance().restoreAll(rootElement);
		
	}
	public void initialize() {
		ReasoningWebDesktop.getInstance().getRootFolder().initialize();
	}
}
