

package gov.va.med.cds.testharness.vhim400;


import gov.va.med.cds.testharness.xml.SchemaHelper;
import gov.va.med.cds.testharness.xml.SchemaHelperException;

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

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.ElementModifier;


public class SchemaBasedElementModifier implements ElementModifier
{
    private String templateId = null;
    private SchemaHelper schemaHelper = null;
    private List<ElementModifier> elementModifiers;


    @Override
    public Element modifyElement( Element element ) throws Exception
    {
        if ( "ClinicalData".equals( element.getName() ) )
        {
            element.element( "templateId" ).setText( this.templateId );
        }

        List<Element> elements = element.elements();
        for ( Element e : elements )
        {
            modifyElement( e );
        }

        // check to see if the element is invalid for the schema
        if ( !schemaHelper.isPathValidForSchema( element.getPath() ) )
        {
            element.detach();
            return null;
        }

        if ( elementModifiers != null )
        {
            for ( ElementModifier secondaryModifier : elementModifiers )
            {
                secondaryModifier.modifyElement( element );
            }
        }
        return element;
    }


    public void setTemplateId( String templateId )
    {
        try
        {
            //establish a path to the templatecache on the file system
            String cdsRoot = System.getenv("CDS_ROOT");  
            String templateCache = System.getProperty( "cds.test.templatecache" );
           
            this.templateId = templateId;
            this.schemaHelper = SchemaHelper.createSchemaHelper( cdsRoot+templateCache, templateId );
        }
        catch ( SchemaHelperException e )
        {
            throw new IllegalArgumentException( "Error initializing Schema Helper instance.", e );
        }

    }


    public void setElementModifiers( List<ElementModifier> elementModifiers )
    {
        this.elementModifiers = elementModifiers;
    }
    
    
    public void addElementModifier( ElementModifier elementModfier )
    {
        if( this.elementModifiers == null)
        {
            this.elementModifiers = new ArrayList<ElementModifier>();
        }
        
        this.elementModifiers.add( elementModfier );
    }

}
