/****************************************************************************
 * Copyright/Copyleft: 
 * 
 * For this source the LGPL Lesser General Public License, 
 * published by the Free Software Foundation is valid.
 * It means:
 * 1) You can use this source without any restriction for any desired purpose.
 * 2) You can redistribute copies of this source to everybody.
 * 3) Every user of this source, also the user of redistribute copies 
 *    with or without payment, must accept this license for further using.
 * 4) But the LPGL ist not appropriate for a whole software product,
 *    if this source is only a part of them. It means, the user 
 *    must publish this part of source,
 *    but don't need to publish the whole source of the own product.
 * 5) You can study and modify (improve) this source 
 *    for own using or for redistribution, but you have to license the
 *    modified sources likewise under this LGPL Lesser General Public License.
 *    You mustn't delete this Copyright/Copyleft inscription in this source file.    
 *
 * @author www.vishia.de/Java
 * @version 2006-06-15  (year-month-day)
 * list of changes: 
 * 2006-05-00 JcHartmut: creation
 *
 ****************************************************************************/
package org.vishia.xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;


import org.vishia.mainCmd.MainCmd;
import org.vishia.mainCmd.MainCmdLoggingStream;
import org.vishia.mainCmd.Report;
import org.vishia.xmlSimple.XmlException;

import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.jdom.DocumentWrapper;


/**This class helps to read XML documents. 
 * The separability to other readers is, more as one XML input file may be read,
 * all input files are joined together in one Document, with an extra root element,
 * named 'root'. Therefore the letter 'M' (multiple) is included in the name of the class. 
 * <br>
 * Inside, partly JDOM is used {@linkplain http:\\www.jdom.org}, but most of the
 * inner working should be based on SAXON {@linkplain http:www.saxonica.com}.
 */
public class XmlMReaderJdomSaxon extends XmlMReader
{

  XmlMReaderJdomSaxon(Report console)
  { super(console);
  }
  
  
  public XmlMReaderJdomSaxon()
  {
    console = MainCmd.getLogging_ifc();
    if(console == null){
      console = new MainCmdLoggingStream(System.out, 3);
    }
  }
  
  

  
  private org.jdom.Element readXmlFileJdom(File fileIn, int mode)
  throws FileNotFoundException, XmlException
  {
    org.jdom.Element xmlInput = null;
    if( (mode & mReplaceWhiteSpaceWith1Space ) != 0)
    { xmlInput = XmlExtensions.readXmlFileTrimWhiteSpace(fileIn);
    }
    else
    { xmlInput = XmlExtensions.readXmlFile(fileIn);
    }
    return xmlInput;
  }
  
  
  
  
  /**Reads the input of all files into a Jdom Element named "root".
   * 
   * @param xmlRoot The element &lt;root> with content of all input files.
   * @return the nr of readed files if all files are readable, or the negativ nr of readed files, if at least one input failes.
   */
  public int readInputsToJdomElement(org.jdom.Element xmlRoot)
  { boolean bOk = true;
    int nReadedFiles = 0;
    
    Iterator<FileTypeIn> iterFileIn = listFileIn.iterator();
    while(iterFileIn.hasNext())
    { //add one xml-tree from the given input file to /root
      FileTypeIn input = iterFileIn.next();
      String sFileIn = input.sName;
      console.writeInfoln("reading " + sFileIn);
      try
      { org.jdom.Element xmlInput = readXmlFileJdom(input.getFile(), input.getMode());
        xmlInput.detach();
        xmlRoot.addContent(xmlInput);
        nReadedFiles += 1;
        console.writeInfo(" ...done.");
      }
      catch(Exception exception)
      { console.writeError("Problem reading " + input.getFile().getAbsolutePath());
        bOk = false;
      }
    }
    return bOk ? nReadedFiles : -nReadedFiles; 
  }
  

  //org.w3c.dom.
  //public net.sf.saxon.om.DocumentInfo readInputsViaJdom(TransformerFactory tfactory)
  @Override public Source readInputs(TransformerFactory tfactory)
  { 
    org.jdom.Document docJdom = new org.jdom.Document();
    org.jdom.Element xmlRoot = new org.jdom.Element("root");
    readInputsToJdomElement(xmlRoot);
    docJdom.setRootElement(xmlRoot);

    String sFirstInputFile = listFileIn.get(0).getFile().getAbsolutePath();
    
    Configuration config = ((TransformerFactoryImpl)tfactory).getConfiguration();
    
    net.sf.saxon.jdom.DocumentWrapper docWrapper 
    = new DocumentWrapper(docJdom, sFirstInputFile, config);
    return docWrapper;
  }
  /*
  net.sf.saxon.om.DocumentInfo readInputsViaAelfred()
  {
    DocumentBuilderFactory dfactory =
        DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try
    {
      docBuilder = dfactory.newDocumentBuilder();
    }
    catch (ParserConfigurationException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
    Document docRoot = docBuilder.newDocument();
    
    SAXParserFactory parserFactory = net.sf.saxon.aelfred.SAXParserFactoryImpl.newInstance();
    SAXParser parser = null;
    try
    {
      parser = parserFactory.newSAXParser();
    }
    catch (ParserConfigurationException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace(); return null;
    }
    catch (SAXException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    org.xml.sax.helpers.DefaultHandler parserHandler = new net.sf.saxon.aelfred.DefaultHandler();
    
    TinyBuilder tree = new TinyBuilder();
    
    
    Iterator iterIn = null; //sFileIn.iterator();
    while(iterIn.hasNext())
    { //FileIn fileIn = (FileIn) iterIn.next();
      try
      {
        parser.parse(fileIn.getFile(), parserHandler); //tree); //parserHandler);
      }
      catch (SAXException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
      }
      catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace(); return null;
      }
      Document inputDocument;
      try
      {
        inputDocument = docBuilder.parse(new InputSource(new FileInputStream(fileIn.getFile())));
      }
      catch (FileNotFoundException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace(); return null;
      }
      catch (SAXException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace(); return null;
      }
      catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace(); return null;
      }
      outputSimple(inputDocument, new File("testi1.out"));
      Node inputNode = inputDocument.getDocumentElement();
      docRoot.adoptNode(inputNode);
    }
    
    return null;    
  }
  */
  
}
