package com.dbxml.db.common.scripting;

/*
 * 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: ScriptExtension.java,v 1.5 2004/08/22 04:18:41 bradford Exp $
 */

import com.dbxml.db.core.DBException;
import com.dbxml.db.core.extension.SimpleExtension;
import com.dbxml.labrador.types.Variant;
import com.dbxml.util.Configuration;
import com.dbxml.util.dbXMLException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * ScriptExtension is the base class for all script-interpreted Extensions.
 * A lot would need to be done here to make this class useful as a dbXML
 * service (ex: Storing the scripts in a collection, pooling, reloading
 * when modified, etc...)
 */

public abstract class ScriptExtension extends SimpleExtension {
   private static final String FILENAME = "filename";

   protected String filename;
   protected String script;

   public void setConfig(Configuration config) throws dbXMLException {
      super.setConfig(config);
      try {
         filename = config.getAttribute(FILENAME);
         if ( filename != null && filename.length() > 0 ) {
            File f = new File(filename);
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis, 4096);
            InputStreamReader isr = new InputStreamReader(bis, "UTF8");
            char[] c = new char[(int)f.length()];
            int size = isr.read(c);
            isr.close();
            script = new String(c, 0, size);
         }
         else
            script = config.getValue();
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
   }

   public static final String[] PARAMS_execute = {"args"};

   /**
    * execute must be implemented by a script-interpreting Extension.
    *
    * @param args Free-form argument list
    * @return The result of the script
    */
   public abstract Variant execute(Map args) throws DBException;
}

