package convert.relaxng.parse.sax;

import convert.xml.sax.XMLReaderCreator;
import convert.relaxng.parse.BuildException;
import convert.relaxng.parse.IllegalSchemaException;
import convert.relaxng.parse.Parseable;
import convert.relaxng.parse.ParsedPattern;
import convert.relaxng.parse.SchemaBuilder;
import convert.relaxng.parse.Scope;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import java.io.IOException;

public class SAXParseable extends SAXSubParser implements Parseable {
  private final InputSource in;

  public SAXParseable(XMLReaderCreator xrc, InputSource in, ErrorHandler eh) {
    super(xrc, eh);
    this.in = in;
  }

  public ParsedPattern parse(SchemaBuilder schemaBuilder, Scope scope) throws BuildException, IllegalSchemaException {
    try {
      XMLReader xr = xrc.createXMLReader();
      SchemaParser sp = new SchemaParser(xr, eh, schemaBuilder, null, scope);
      xr.parse(in);
      return sp.getParsedPattern();
    }
    catch (SAXException e) {
      throw toBuildException(e);
    }
    catch (IOException e) {
      throw new BuildException(e);
    }
  }

}
