/* $Id: SmartDocument.java 653 2013-02-08 09:35:06Z ohura $ */
package smart_gs.logical;

import java.util.ArrayList;
import java.util.List;

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


public abstract class SmartDocument extends GSResource{

	
	protected String source;
	protected List<TextSegment> segments;

	public SmartDocument() {
		super();
		this.source ="<sml></sml>";
		this.segments = new ArrayList<TextSegment>();
	}
	public SmartDocument(String source){
		super();
		this.source = source;
		this.segments = new ArrayList<TextSegment>();		
	}
	public List<TextSegment> getSegments(){
		return this.segments;
	}
	public String getSource(){
		return this.source;
	}
	/**
	 * @param string
	 */
	public void setSource(String source) {
		this.source = source;
	}
	public void addTextSegment(TextSegment segment) {
		this.segments.add(segment);
	}
	public void removeTextSegment(int id){
		for(int i=0;i<this.segments.size();i++){
			if(id == this.segments.get(i).getId()){
				this.segments.remove(i);
				return;
			}
		}
	}
	public TextSegment getSegmentByID(int id) {
		for(int i=0;i<this.segments.size();i++){
			if(id == this.segments.get(i).getId()){
				return this.segments.get(i);
			}
		}
		return null;
	}
	public GSResource getSegments(String uri) {
		for(int i=0;i<this.segments.size();i++){
			if(this.segments.get(i).getURI().equals(uri)){
				return this.segments.get(i);
			}
		}
		return null;
	}
	protected void checkSegments(Element element){
		NodeList list = element.getChildNodes();
		for(int i=0;i<list.getLength();i++){
			if(list.item(i).getNodeType() == Node.ELEMENT_NODE){
				Element elem = (Element)list.item(i);
				if(elem.hasAttribute("id")){
					String id = elem.getAttribute("id");
					if(this.hasSegment(new Integer(id))){
						continue;
					}
					String tagname = elem.getNodeValue();
					TextSegment segment = new TextSegment(tagname,this,new Integer(id));
					this.addTextSegment(segment);
				}
				this.checkSegments(elem);
			}
		}
		
	}
	private boolean hasSegment(int id) {
		for(int i=0;i<this.segments.size();i++){
			if(this.segments.get(i).getId() == id){
				return true;
			}
		}
		return false;
	}
	public boolean isIDAT() {
		return this.getTypeString().equals(URIObject.FIRST_IDAT)
			|| this.getTypeString().equals(URIObject.SECOND_IDAT)
			|| this.getTypeString().equals(URIObject.THIRD_IDAT);
	}
	
	
}
