package com.tinkerpop.rexster.protocol.msg;

import com.tinkerpop.rexster.gremlin.converter.ConsoleResultConverter;
import com.tinkerpop.rexster.protocol.BitWorks;
import org.msgpack.annotation.Message;

import javax.script.Bindings;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

@Message
public class ConsoleScriptResponseMessage extends RexProMessage {
    public static final byte FLAG_COMPLETE_MESSAGE = 0;

    public String[] ConsoleLines;
    public byte[] Bindings;

    public List<String> ConsoleLinesAsList() {
        List<String> list = new ArrayList<String>();
        for (String line : ConsoleLines) {
            list.add(line);
        }

        return list;
    }

    public List<String> BindingsAsList() {
        List<String> bindings = new ArrayList<String>();

        ByteBuffer bb = ByteBuffer.wrap(this.Bindings);

        while (bb.hasRemaining()) {
            int segmentLength = bb.getInt();
            byte[] segmentBytes = new byte[segmentLength];
            bb.get(segmentBytes);

            bindings.add(new String(segmentBytes));
        }

        return bindings;
    }

    public static byte[] convertBindingsToByteArray(Bindings bindings) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        for (String key : bindings.keySet()) {
            baos.write(BitWorks.convertStringsToByteArray(key + "=" + bindings.get(key).toString()));
        }

        return baos.toByteArray();
    }

    public static List<String> convertResultToConsoleLines(Object result) throws Exception {
        ConsoleResultConverter converter = new ConsoleResultConverter(new StringWriter());
        return converter.convert(result);
    }
}

@@ -1331,24 +1331,30 @@
 n %7B%0A        
+final 
 ByteArrayOut
@@ -1443,24 +1443,74 @@
 keySet()) %7B%0A
+            final Object val = bindings.get(key);%0A
             
@@ -1567,33 +1567,43 @@
 + %22=%22 + 
-bindings.get(key)
+(val == null ? %22null%22 : val
 .toStrin
@@ -1607,16 +1607,17 @@
 ring()))
+)
 ;%0A      

Handle nulls in bindings for RexterConsole.