package org.cratedb.action.collect;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.util.BytesRef;
import org.cratedb.DataType;
import org.elasticsearch.index.fielddata.BytesValues;
import org.elasticsearch.index.fielddata.IndexFieldData;

public class BytesRefColumnReference extends FieldCacheExpression<IndexFieldData, BytesRef> {

    private BytesValues values;

    public BytesRefColumnReference(String columnName) {
        super(columnName);
    }

    @Override
    public BytesRef evaluate() {
        return values.getValue(docId);
    }

    @Override
    public void setNextReader(AtomicReaderContext context) {
        super.setNextReader(context);
        values = indexFieldData.load(context).getBytesValues();
    }

    @Override
    public DataType returnType(){
        return DataType.STRING;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (!(obj instanceof BytesRefColumnReference))
            return false;
        return columnName.equals(((BytesRefColumnReference) obj).columnName);
    }

    @Override
    public int hashCode() {
        return columnName.hashCode();
    }
}


@@ -536,22 +536,28 @@
         
-return
+BytesRef v =
  values.
@@ -573,16 +573,111 @@
 docId);%0A
+        if (v != null) %7B%0A            return values.makeSafe(v);%0A        %7D%0A        return null;%0A
     %7D%0A%0A 
@@ -905,16 +905,17 @@
 rnType()
+ 
 %7B%0A      

make bytesref expression return safe values