package convert.relaxng.input.parse;

import convert.relaxng.input.InputFormat;
import convert.relaxng.input.InputFailedException;
import convert.relaxng.edit.SchemaCollection;
import convert.relaxng.parse.Parseable;
import convert.relaxng.parse.IllegalSchemaException;
import convert.relaxng.translate.util.InvalidParamsException;
import convert.relaxng.translate.util.ParamProcessor;
import convert.relaxng.translate.util.EncodingParam;
import convert.datatype.DatatypeLibraryLoader;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;

public abstract class ParseInputFormat implements InputFormat {
  private final boolean commentsNeedTrimming;
  protected ParseInputFormat(boolean commentsNeedTrimming) {
    this.commentsNeedTrimming = commentsNeedTrimming;
  }

  public SchemaCollection load(String uri, String[] params, String outputFormat, ErrorHandler eh)
          throws InputFailedException, InvalidParamsException, IOException, SAXException {
    final InputSource in = new InputSource(uri);
    ParamProcessor pp = new ParamProcessor();
    pp.declare("encoding",
               new EncodingParam() {
                 protected void setEncoding(String encoding) {
                   in.setEncoding(encoding);
                 }
               });
    pp.process(params, eh);
    Parseable parseable = makeParseable(in, eh);
    try {
      return SchemaBuilderImpl.parse(parseable,
                                     uri,
                                     eh,
                                     new DatatypeLibraryLoader(),
                                     commentsNeedTrimming);
    }
    catch (IllegalSchemaException e) {
      throw new InputFailedException();
    }
  }

  protected abstract Parseable makeParseable(InputSource in, ErrorHandler eh);
}
