// $Id: ZipFileToSingleFile.java 6811 2010-07-23 16:57:28Z nigelw $
// Copyright (c) 2010 DeltaXML Ltd. All rights reserved
/*  This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License version 3 only,
    as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License version 3 for more details
    (a copy is included in the LICENSE-LGPL.txt file that accompanied this code).

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/> */
package com.deltaxml.odf.ct;

import java.io.File;
import java.io.InputStream;
import java.util.zip.ZipFile;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.InputSource;

public class ZipFileToSingleFile {
  
  private final String CONTENT= "content.xml";
  private final String FILE_CONVERT= "xsl/odf-zip-to-single-file.xsl";
  
  public void convert(File input, File single) throws Exception {
    
    ZipFile zip= new ZipFile(input);
    
    InputStream mimetypeFile= zip.getInputStream(zip.getEntry("mimetype"));
    StringBuffer mimetype= new StringBuffer();
    int c;
    while((c = mimetypeFile.read()) != -1) {
      mimetype.append((char)c);
    }
    
    mimetypeFile.close();
    
    InputStream content= zip.getInputStream(zip.getEntry(CONTENT));
    InputSource contentSrc= new InputSource(content);
    contentSrc.setSystemId(input.toURI().toString());
    
    TransformerFactory tf= TransformerFactory.newInstance();
    Transformer t= tf.newTransformer(new StreamSource(this.getClass().getClassLoader().getResourceAsStream(FILE_CONVERT)));
    t.setParameter("mimetype", mimetype.toString());
    t.setURIResolver(new OdtUriResolver());
    
    t.transform(new SAXSource(contentSrc), new StreamResult(single));
  }
  
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Usage: " + ZipFileToSingleFile.class.getCanonicalName() + " zipfile-input xml-output");
    }
    
    ZipFileToSingleFile converter= new ZipFileToSingleFile();
    File input= new File(args[0]);
    File single= new File(args[1]);
    converter.convert(input, single);
  }
  
}
