/* $Id: SmartDocument.java 1096 2016-04-20 13:44:12Z shayashi $ */
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;
	protected List<TextSegment> removed_segments;

	public SmartDocument() {
		super();
		this.source ="<sml></sml>";
		this.segments = new ArrayList<TextSegment>();
		this.removed_segments = new ArrayList<TextSegment>();
	}
	public SmartDocument(String source){
		super();
		this.source = source;
		this.segments = new ArrayList<TextSegment>();		
		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()){
				TextSegment seg = this.segments.get(i);
				if (! this.removed_segments.contains(seg)) this.removed_segments.add(seg);
				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 TextSegment getZombieSegmentByID(int id) {
		for(int i=0;i<this.removed_segments.size();i++){
			if(id == this.removed_segments.get(i).getId()){
				return this.removed_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)
			|| this.getTypeString().equals(URIObject.OCR_IDAT);
	}

	
	
}
