package com.dbxml.db.core.indexer;

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

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import com.dbxml.db.core.data.Value;
import com.dbxml.util.ByteArray;

/**
 * IndexValue
 */

public final class IndexValue extends Value {
   private static final Value EmptyValue = new Value(new byte[0]);

   public IndexValue(Value value, Value extra) {
      int vs = value.getLength();
      int es = extra.getLength();
      int size;
      if ( es > 0 )
         size = vs+es+3;
      else
         size = vs+2;

      try {
         ByteArrayOutputStream bos = new ByteArrayOutputStream(size);
         DataOutputStream dos = new DataOutputStream(bos);
         dos.write(value.getRawData(), value.getOffset(), vs);
         dos.writeByte(0);
         dos.write(extra.getRawData(), extra.getOffset(), es);
         dos.writeShort(vs);
         data = bos.toByteArray();
         pos = 0;
         len = data.length;
      }
      catch ( Exception e ) {
         // Won't Happen
      }
   }

   public IndexValue(Value value) {
      this(value, EmptyValue);
   }

   public IndexValue(byte[] data) {
      super(data);
   }

   public IndexValue(byte[] data, int pos, int len) {
      super(data, pos, len);
   }

   public Value getIndexValue() {
      return getIndexValue(this);
   }

   public static Value getIndexValue(Value value) {
      byte[] b = value.getRawData();
      int pos = value.getOffset();
      int len = value.getLength();
      int valLen = ByteArray.readShort(b, (pos+len)-2);
      return new Value(b, pos, valLen);
   }

   public Value getExtraValue() {
      return getExtraValue(this);
   }

   public static Value getExtraValue(Value value) {
      byte[] b = value.getRawData();
      int pos = value.getOffset();
      int len = value.getLength();
      int valLen = ByteArray.readShort(b, (pos+len)-2);
      if ( valLen < len-2 ) {
         // Take into account the null separator
         return new Value(b, pos+valLen+1, (len-valLen)-3);
      }
      else
         return EmptyValue;
   }
}
