package org.dbxml.core.system;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: Sequencer.java,v 1.2 2001/07/16 03:59:01 tom Exp $
 */

import org.dbxml.core.*;
import org.dbxml.core.Collection;
import org.dbxml.core.objects.*;
import org.dbxml.xml.*;
import org.dbxml.xml.dom.*;

import java.util.*;

import org.w3c.dom.*;

/**
 * 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 SimpleXMLObject {
   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 HashMap());
   private boolean loaded = false;
   private Collection sysObj;
   private String docKey;
   private DocumentImpl doc;
   
   public Sequencer() {
   }

   private void checkLoaded() {
      if ( loaded )
         return;
      try {
         sysObj = collection.getSystemCollection().getCollection(SystemCollection.OBJECTS);
         docKey = PREFIX + collection.getCanonicalName();
         doc = (DocumentImpl)sysObj.getDocument(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 = new DocumentImpl();
            doc.setSymbols(sysObj.getSymbols());
            doc.appendChild(doc.createElement(SEQUENCES));
         }
         loaded = true;
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }
   }
   
   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;
   }

   private void write() {
      try {
         sysObj.setDocument(docKey, doc);
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }
   }

   
   /**
    * 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();
      }
   }
}


