package com.dbxml.db.client.xmldb;

/*
 * 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: XSLTransformServiceImpl.java,v 1.3 2004/02/12 00:17:56 bradford Exp $
 */

import com.dbxml.db.client.CollectionClient;
import com.dbxml.db.client.ResultSetClient;
import com.dbxml.db.common.xslt.XSLTQueryResolver;
import com.dbxml.db.core.query.Query;
import com.dbxml.util.dbXMLException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;

/**
 * XSLTransformServiceImpl
 */

public final class XSLTransformServiceImpl extends QueryServiceImpl implements XSLTransformService {
   private static final String NAME = "XSLTransformService";
   private static final String STYLE = XSLTQueryResolver.STYLE_XSLT;
   private static final String VERSION = "1.0";

   private Map params = Collections.synchronizedMap(new LinkedHashMap());
   private XMLResource templates;

   public XSLTransformServiceImpl(CollectionImpl col) {
      super(col, STYLE);
   }

   public String getName() throws XMLDBException {
      return NAME;
   }

   public String getVersion() throws XMLDBException {
      return VERSION;
   }

   public void setTemplates(XMLResource templates) throws XMLDBException {
      this.templates = templates;
   }

   public void setParameter(String name, String value) throws XMLDBException {
      params.put(name, value);
   }

   public String getParameter(String name) throws XMLDBException {
      return (String)params.get(name);
   }

   public void removeParameter(String name) throws XMLDBException {
      params.remove(name);
   }

   public void clearParameters() throws XMLDBException {
      params.clear();
   }

   private String getQuery(String xpath, String id) throws XMLDBException {
      try {
         StringBuffer sb = new StringBuffer();
         sb.append("<dbxml:xslt xmlns:dbxml=\""+Query.NSURI+"\">\n");
         sb.append("   <dbxml:source");
         if ( xpath != null )
            sb.append(" xpath=\"\"");
         if ( id != null )
            sb.append(" document=\"\"");
         sb.append("/>\n");
         if ( params.size() > 0 ) {
            sb.append("   <dbxml:params>\n");
            Iterator iter = params.entrySet().iterator();
            while ( iter.hasNext() ) {
               Map.Entry entry = (Map.Entry)iter.next();
               String key = (String)entry.getKey();
               String value = (String)entry.getValue();
               sb.append("      <param name=\""+key+"\" value=\""+value+"\">\n");
            }
            sb.append("   </dbxml:params>\n");
         }

         if ( templates != null ) {
            Collection parent = templates.getParentCollection();
            if ( parent instanceof CollectionImpl ) {
               CollectionImpl impl = (CollectionImpl)parent;
               CollectionClient cli = impl.getCollectionClient();
               String path = cli.getCanonicalName()+"/"+templates.getId();
               sb.append("   <dbxml:stylesheet document=\""+path+"\"/>\n");
            }
            else {
               sb.append("   <dbxml:stylesheet>\n");
               sb.append((String)templates.getContent());
               sb.append("   </dbxml:stylesheet>\n");
            }
         }
         sb.append("</dbxml:xslt>");
         return sb.toString();
      }
      catch ( dbXMLException e ) {
         throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage());
      }
   }

   private Resource getResource(ResultSetClient rs) throws XMLDBException {
      try {
         Resource resource = null;
         if ( rs.next() ) {
            String docID = rs.getResultKey();
            String id = Integer.toString(new Object().hashCode());
            String xml = rs.getResultAsText();
            resource = new XMLResourceImpl(col, docID, id, xml);
         }
         rs.close();
         return resource;
      }
      catch ( dbXMLException e ) {
         throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage());
      }
   }

   public Resource transform(String xpath) throws XMLDBException {
      return getResource(performQuery(getQuery(xpath, null)));
   }

   public Resource transformResource(String id) throws XMLDBException {
      return getResource(performQueryResource(getQuery(null, id), id));
   }
}
