// $Id: OdtUriResolver.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.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;

public class OdtUriResolver implements URIResolver {
  
  public Source resolve(String href, String base) throws TransformerException {
//    System.out.println("RESOLVE -  href: '" + href + " base: '" + base + "'");
    if (base.endsWith(".odt") || base.endsWith(".ods")) {
      //we are looking for a file within an odt file, access it using the ZipFile interface
      try {
        File f= new File(new URI(base).getPath());
        ZipFile zf= new ZipFile(f);
        ZipEntry entry= zf.getEntry(href.startsWith("./") ? href.substring(2) : href);
        return new StreamSource(zf.getInputStream(entry));
      } catch (URISyntaxException use) {
        throw new TransformerException("Cannot locate or process ODT file", use);
      } catch (IOException ioe) {
        throw new TransformerException("IO Exception locating ODT contents", ioe);
      }
    }
    return null;
  }
  
}
