package eu.dnetlib.data.collective.transformation.core.schema.visitor;

import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.lang3.NotImplementedException;

import com.sun.xml.xsom.XSAttributeUse;
import com.sun.xml.xsom.XSContentType;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSSimpleType;
import com.sun.xml.xsom.XSType;
import com.sun.xml.xsom.visitor.XSContentTypeVisitor;

import eu.dnetlib.data.collective.transformation.core.schema.SchemaAttribute;
import eu.dnetlib.data.collective.transformation.core.schema.SchemaElement;

/**
 * @author jochen
 *
 */
public class XSContentTypeVisitorImpl implements XSContentTypeVisitor {

	private Visitor visitor;
	
	@Override
	public void empty(XSContentType arg0) {
		throw new NotImplementedException("TODO empty");
	}

	@Override
	public void particle(XSParticle aParticle) {
		XSTermVisitorImpl termVisitor = new XSTermVisitorImpl();
		termVisitor.setVisitor(this.visitor);
		aParticle.getTerm().visit(termVisitor);		
		if (aParticle.getTerm().isElementDecl()){
			XSElementDecl elem = aParticle.getTerm().asElementDecl();						
			SchemaElement element = new SchemaElement();

			XSType type = elem.getType();
			if (type.isComplexType()){
				Collection<? extends XSAttributeUse> attrColls = 
						type.asComplexType().getDeclaredAttributeUses();
				Iterator<? extends XSAttributeUse> attrIter = attrColls.iterator();
				while (attrIter.hasNext()){
					XSAttributeUse attrUse = attrIter.next();
					SchemaAttribute attribute = new SchemaAttribute();
					attribute.setName(attrUse.getDecl().getName());
					attribute.setRequired(attrUse.isRequired());
					element.addAttribute(attribute);					
				}
			}
			element.setName(elem.getName());
			element.setTargetNamespace(elem.getTargetNamespace());
			element.setMinOccurs(aParticle.getMinOccurs().intValue());
			element.setMaxOccurs(aParticle.getMaxOccurs().intValue());
			element.setRepeatable(aParticle.isRepeated());
			
			if (elem.getType().isComplexType()){
				if (elem.getType().asComplexType().getContentType().asSimpleType() != null){
					element.setContainsSimpleType(true);
				}
			}			
			this.visitor.getCurrentElement().getChildList().add(element);
		}
	}

	@Override
	public void simpleType(XSSimpleType arg0) {
		throw new NotImplementedException("TODO simpleType");
	}

	public void setVisitor(Visitor visitor) {
		this.visitor = visitor;
	}

	public Visitor getVisitor() {
		return visitor;
	}

}