package com.dbxml.db.common.xslt;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: XSLTQueryResolver.java,v 1.4 2004/03/09 00:12:08 bradford Exp $
 */

import javax.xml.transform.*;

import com.dbxml.db.client.ContentClient;
import com.dbxml.db.client.dbXMLClient;
import com.dbxml.db.client.local.CollectionClientImpl;
import com.dbxml.db.client.local.dbXMLClientImpl;
import com.dbxml.db.common.query.QueryBase;
import com.dbxml.db.common.query.QueryResolverBase;
import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.data.RecordMetaData;
import com.dbxml.db.core.query.CompilationException;
import com.dbxml.db.core.query.QueryException;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.util.SoftHashMap;
import com.dbxml.xml.NamespaceMap;
import java.io.StringReader;
import java.net.URL;
import java.util.Map;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;

/**
 * XSLTQueryResolver
 */

public final class XSLTQueryResolver extends QueryResolverBase {
   public static final String STYLE_XSLT = "XSLT";
   static final String URL_PREFIX = "http://";

   private Map cache = new SoftHashMap();
   private dbXMLClient client = new dbXMLClientImpl();
   private XSLTURIResolver uriResolver = new XSLTURIResolver();
   private TransformerFactory tf;

   public XSLTQueryResolver() {
      tf = TransformerFactory.newInstance();
   }

   public String getQueryStyle() {
      return STYLE_XSLT;
   }

   public QueryBase createQuery(Collection context, String query, NamespaceMap nsMap, Key[] keys) throws QueryException {
      return new XSLTQuery(context, query, nsMap, keys, this);
   }

   Transformer getTransformer(Source source) throws QueryException {
      try {
         Transformer t = tf.newTransformer(source);
         t.setURIResolver(uriResolver);
         return t;
      }
      catch ( Exception e ) {
         if ( e instanceof QueryException )
            throw (QueryException)e;
         else
            throw new CompilationException("Couldn't compile XSLT Query", e);
      }
   }

   Transformer getTransformer(String path) throws QueryException {
      Transaction tx = new Transaction();

      int idx = path.lastIndexOf('/');
      String colName = path.substring(0, idx);
      String docName = path.substring(idx + 1);

      try {
         CollectionClientImpl col = (CollectionClientImpl)client.getCollection(colName);
         if ( col == null )
            throw new CompilationException("Template Collection '" + colName + "' not found");

         RecordMetaData meta = col.getInternalCollection().getRecordMetaData(tx, new Key(docName));
         long lastModified = System.currentTimeMillis();
         if ( meta != null ) {
            Long lm = (Long)meta.getValue(RecordMetaData.MODIFIED);
            if ( lm != null )
               lastModified = lm.longValue();
         }

         TemplatesInfo info = (TemplatesInfo)cache.get(path);
         if ( info == null || info.lastModified != lastModified ) {
            Document doc = col.getDocument(docName);
            String systemID = URL_PREFIX+colName+"/"+docName;
            Source src = new DOMSource(doc, systemID);
            Templates t = tf.newTemplates(src);

            info = new TemplatesInfo(path, lastModified, t);
            cache.put(path, info);
         }

         Transformer transformer = info.tmp.newTransformer();
         transformer.setURIResolver(uriResolver);
         return transformer;
      }
      catch ( Exception e ) {
         try {
            tx.cancel();
         }
         catch ( DBException ex ) {
            ex.printStackTrace(System.err);
         }

         if ( e instanceof QueryException )
            throw (QueryException)e;
         else
            throw new CompilationException("Couldn't compile XSLT Query", e);
      }
      finally {
         if ( tx.getStatus() == Transaction.ACTIVE ) {
            try {
               tx.commit();
            }
            catch ( DBException e ) {
               e.printStackTrace(System.err);
            }
         }
      }
   }


   /**
    * TemplatesInfo
    */

   private class TemplatesInfo {
      public String path;
      public long lastModified;
      public Templates tmp;

      public TemplatesInfo(String path, long lastModified, Templates tmp) {
         this.path = path;
         this.lastModified = lastModified;
         this.tmp = tmp;
      }
   }


   /**
    * XSLTURIResolver
    */

   private class XSLTURIResolver implements URIResolver {
      public XSLTURIResolver() {
      }

      public Source resolve(String href, String base) throws TransformerException {
         if ( href.indexOf("://") == -1 ) {
            try {
               URL baseURL = new URL(base);
               URL combURL = new URL(baseURL, href);
               String path = combURL.getPath();

               ContentClient content = client.getContent(path);
               String doc = content.getDocumentAsText();
               StringReader sr = new StringReader(doc);
               String systemID = URL_PREFIX+path;

               return new StreamSource(sr, systemID);
            }
            catch ( Exception e ) {
               //throw new TransformerException(e);
               return null;
            }
         }
         else
            return null;
      }
   }
}

