package com.dbxml.db.server.labrador;

/*
 * 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: ContentProxy.java,v 1.5 2004/02/12 00:17:58 bradford Exp $
 */

import com.dbxml.db.core.Collection;
import com.dbxml.db.core.Container;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.FaultCodes;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.data.RecordMetaData;
import com.dbxml.db.core.data.Value;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.labrador.Endpoint;
import com.dbxml.labrador.Handler;
import com.dbxml.labrador.Headers;
import com.dbxml.labrador.Request;
import com.dbxml.labrador.Response;
import com.dbxml.labrador.broker.Broker;
import com.dbxml.labrador.broker.BrokerContext;
import com.dbxml.labrador.http.HTTP;
import com.dbxml.labrador.http.HTTPException;
import com.dbxml.labrador.http.HTTPServerBase;
import com.dbxml.labrador.rest.RESTHandler;
import com.dbxml.util.UTF8;
import com.dbxml.xml.dtsm.DTSMException;
import com.dbxml.xml.dtsm.DTSMHelper;
import com.dbxml.xml.dtsm.DocumentTable;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * ContentProxy is a proxy facade that is used to expose Content
 * functionality via Labrador.
 */

public final class ContentProxy {
   private static final SimpleDateFormat GDF = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss 'GMT'", new DateFormatSymbols(Locale.US));

   public static final String REST_DEFAULT_METHOD = "get";

   public static final String NAME = "name";
   public static final String COL_NAME = "colName";
   public static final String CANONICAL_NAME = "canonicalName";
   public static final String CONTENT_TYPE = "contentType";

   private Collection col;
   private String docName;
   private int type;

   public ContentProxy(Collection col, String docName) {
      this.col = col;
      this.docName = docName;
      if ( col.getCollectionType() == Collection.TYPE_DOCUMENTS )
         type = Container.TYPE_DOCUMENT;
      else
         type = Container.TYPE_VALUE;
   }

   public Map getInformation() throws DBException {
      Map result = new HashMap(4);
      result.put(NAME, docName);
      result.put(COL_NAME, col.getCanonicalName());
      result.put(CANONICAL_NAME, col.getCanonicalDocumentName(new Key(docName)));
      result.put(CONTENT_TYPE, new Integer(type));
      return result;
   }

   public byte[] get() throws HTTPException, DBException {
      Transaction tx = new Transaction();

      try {
         Key key = new Key(docName);

         // Let's see if we can interact with Labrador's HTTP Server for REST calls
         BrokerContext context = Broker.getInstance().getBrokerContext();
         Handler handler = context.getHandler();
         Endpoint endpoint = context.getRequestEndpoint();

         boolean restHandler = handler instanceof RESTHandler;
         boolean httpEndpoint = endpoint instanceof HTTPServerBase;

         if ( restHandler && httpEndpoint ) {
            Request request = context.getRequest();
            Response response = context.getResponse();

            RecordMetaData meta = col.getRecordMetaData(tx, key);
            if ( meta != null ) {
               Long lm = (Long)meta.getValue(RecordMetaData.MODIFIED);
               if ( lm != null ) {
                  String lastModified = GDF.format(new Date(lm.longValue()));

                  response.setHeader(HTTP.HEADER_CACHE_CONTROL, HTTP.VALUE_CACHE);
                  response.setHeader(HTTP.HEADER_LAST_MODIFIED, lastModified);

                  String since = request.getHeader(HTTP.HEADER_IF_MODIFIED_SINCE);
                  if ( since != null && since.length() > 0 && since.equals(lastModified) )
                     throw new HTTPException(HTTP.CODE_NOT_MODIFIED, HTTP.STATUS_NOT_MODIFIED);
               }
            }
         }

         if ( type == Container.TYPE_DOCUMENT ) {
            if ( restHandler )
               context.setProperty(RESTHandler.CONTENT_TYPE, Headers.TYPE_TEXT_XML);

            String doc = DTSMHelper.tableToText(col.getDocument(tx, docName));
            return UTF8.toUTF8(doc);
         }
         else
            return col.getRecord(tx, docName).getValue().getData();
      }
      catch ( DTSMException e ) {
         tx.cancel();
         //e.printStackTrace(System.err);
         throw new DBException(FaultCodes.COL_CANNOT_RETRIEVE, "Can't retrieve '" + docName + "'", e);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
      finally {
         if ( tx.getStatus() == Transaction.ACTIVE )
            tx.commit();
      }
   }

   public static final String REST_CONTENT_TYPE_getDocument = Headers.TYPE_TEXT_XML;

   public String getDocument() throws DBException {
      Transaction tx = new Transaction();
      try {
         return DTSMHelper.tableToText(col.getDocument(tx, docName));
      }
      catch ( DTSMException e ) {
         tx.cancel();
         throw new DBException(FaultCodes.COL_CANNOT_RETRIEVE, "Can't retrieve '" + docName + "'", e);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
      finally {
         if ( tx.getStatus() == Transaction.ACTIVE )
            tx.commit();
      }
   }

   public byte[] getValue() throws DBException {
      Transaction tx = new Transaction();
      try {
         return col.getRecord(tx, docName).getValue().getData();
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
      finally {
         if ( tx.getStatus() == Transaction.ACTIVE )
            tx.commit();
      }
   }

   public static final String[] PARAMS_setDocument = {"document"};

   public void setDocument(String document) throws DBException {
      Transaction tx = new Transaction();
      try {
         DocumentTable dt = DTSMHelper.textToTable(document, col.getSymbols());
         col.setDocument(tx, docName, dt);
      }
      catch ( DTSMException e ) {
         tx.cancel();
         throw new DBException(FaultCodes.COL_CANNOT_STORE, "Can't parse Document '" + docName + "'", e);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
      finally {
         if ( tx.getStatus() == Transaction.ACTIVE )
            tx.commit();
      }
   }

   public static final String[] PARAMS_setValue = {"value"};

   public void setValue(byte[] value) throws DBException {
      Transaction tx = new Transaction();
      try {
         col.setRecord(tx, docName, new Value(value));
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
      finally {
         if ( tx.getStatus() == Transaction.ACTIVE )
            tx.commit();
      }
   }
}

