package com.dbxml.db.core.system;

/*
 * 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: Sequencer.java,v 1.2 2004/02/12 00:17:57 bradford Exp $
 */

import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.SystemCollection;
import com.dbxml.db.core.extension.SimpleExtension;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.xml.dom.DOMHelper;
import com.dbxml.xml.dtsm.DTSMHelper;
import com.dbxml.xml.dtsm.DocumentTable;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * Sequencer is a system-level sequencer for creating auto-incrementing
 * values.  It operates in a similar fashion to how Interbase performs
 * auto-incrementing.  You use the methods to create and retrieve values
 * from named sequences.  These sequences don't have to be explicitly
 * associated with any particular Collection, which allows them to be
 * shared between Collections, or even Databases and Servers for that
 * matter.
 */

public final class Sequencer extends SimpleExtension {
   private static final String[] EmptyStrings = new String[0];

   private static final String PREFIX = "[sequencer]";
   private static final String SEQUENCES = "sequences";
   private static final String SEQUENCE = "sequence";
   private static final String NAME = "name";
   private static final String VALUE = "value";

   private Map values = Collections.synchronizedMap(new TreeMap());
   private boolean loaded;
   private Collection sysObj;
   private String docKey;
   private Document doc;

   public Sequencer() {
   }

   private void checkLoaded() {
      if ( loaded )
         return;

      Transaction tx = new Transaction();
      try {
         sysObj = collection.getSystemCollection().getCollection(SystemCollection.OBJECTS);
         docKey = PREFIX + collection.getCanonicalName();
         doc = (Document)sysObj.getDocument(tx, docKey);
         if ( doc != null ) {
            Element e = doc.getDocumentElement();
            NodeList nl = e.getElementsByTagName(SEQUENCE);
            for ( int i = 0; i < nl.getLength(); i++ ) {
               Element elem = (Element)nl.item(i);
               String name = elem.getAttribute(NAME);
               long val = Long.parseLong(elem.getAttribute(VALUE));
               values.put(name, new SequenceValue(elem, val));
            }
         }
         else {
            doc = DOMHelper.newDocument();
            doc.appendChild(doc.createElement(SEQUENCES));
         }
         loaded = true;
      }
      catch ( Exception e ) {
         try {
             tx.cancel();
         }
         catch ( DBException ex ) {
            e.printStackTrace(System.err);
         }
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE ) {
				try {
					 tx.commit();
				}
				catch ( DBException e ) {
					e.printStackTrace(System.err);
				}
			}
		}
   }

   public static final String[] PARAMS_create = {"name"};

   public void create(String name) {
      checkLoaded();
      SequenceValue sv = (SequenceValue)values.get(name);
      if ( sv == null ) {
         Element elem = doc.createElement(SEQUENCE);
         elem.setAttribute(NAME, name);
         elem.setAttribute(VALUE, "0");
         doc.getDocumentElement().appendChild(elem);
         values.put(name, new SequenceValue(elem, 0));
         write();
      }
   }

   public static final String[] PARAMS_createValue = {"name", "value"};

   public void createValue(String name, long value) {
      checkLoaded();
      SequenceValue sv = (SequenceValue)values.get(name);
      if ( sv == null ) {
         Element elem = doc.createElement(SEQUENCE);
         elem.setAttribute(NAME, name);
         elem.setAttribute(VALUE, Long.toString(value));
         doc.getDocumentElement().appendChild(elem);
         values.put(name, new SequenceValue(elem, value));
         write();
      }
   }

   public static final String[] PARAMS_remove = {"name"};

   public void remove(String name) {
      checkLoaded();
      SequenceValue sv = (SequenceValue)values.get(name);
      if ( sv != null ) {
         doc.removeChild(sv.elem);
         values.remove(name);
         write();
      }
   }

   public static final String[] PARAMS_reset = {"name", "value"};

   public void reset(String name, long value) {
      checkLoaded();
      SequenceValue sv = (SequenceValue)values.get(name);
      if ( sv != null )
         sv.reset(value);
   }

   public static final String[] PARAMS_next = {"name", };

   public long next(String name) {
      checkLoaded();
      SequenceValue sv = (SequenceValue)values.get(name);
      if ( sv != null )
         return sv.next();
      else
         return -1;
   }

   public String[] list() {
      checkLoaded();
      return (String[])values.keySet().toArray(EmptyStrings);
   }

   private void write() {
      Transaction tx = new Transaction();
      try {
         DocumentTable dt = DTSMHelper.documentToTable(doc, sysObj.getSymbols());
         sysObj.setDocument(tx, docKey, dt);
      }
      catch ( Exception e ) {
         try {
             tx.cancel();
         }
         catch ( DBException ex ) {
            e.printStackTrace(System.err);
         }
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE ) {
				try {
					 tx.commit();
				}
				catch ( DBException e ) {
					e.printStackTrace(System.err);
				}
			}
		}
   }


   /**
    * SequenceValue
    */

   private class SequenceValue {
      private Element elem;
      private long value;

      public SequenceValue(Element elem) {
         this.elem = elem;
         value = 0;
      }

      public SequenceValue(Element elem, long value) {
         this.elem = elem;
         this.value = value;
      }

      public synchronized void reset(long value) {
         this.value = value;
         write();
      }

      public synchronized long next() {
         value++;
         write();
         return value;
      }

      private void write() {
         elem.setAttribute(VALUE, Long.toString(value));
         Sequencer.this.write();
      }
   }
}


