/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.elasticsearch.hadoop.cascading;

import java.util.List;

import org.elasticsearch.hadoop.serialization.Generator;
import org.elasticsearch.hadoop.serialization.JdkValueWriter;
import org.elasticsearch.hadoop.serialization.ValueWriter;

import cascading.scheme.SinkCall;
import cascading.tuple.Tuple;

/**
 * Basic delegate around {@link JdkValueWriter} that handles the unwraping of {@link SinkCall}
 */
public class CascadingValueWriter implements ValueWriter<SinkCall<Object[], ?>> {

    private final ValueWriter<Object> jdkWriter;

    public CascadingValueWriter() {
        this(false);
    }

    public CascadingValueWriter(boolean writeUnknownTypes) {
        jdkWriter = new JdkValueWriter(writeUnknownTypes);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean write(SinkCall<Object[], ?> sinkCall, Generator generator) {
        Tuple tuple = sinkCall.getOutgoingEntry().getTuple();
        List<String> names = (List<String>) sinkCall.getContext()[0];

        generator.writeBeginObject();
        for (int i = 0; i < tuple.size(); i++) {
            String name = (i < names.size() ? names.get(i) : "tuple" + i);
            generator.writeFieldName(name);
            if (!jdkWriter.write(tuple.getObject(i), generator)) {
                return false;
            }
        }
        generator.writeEndObject();
        return true;
    }
}

@@ -678,16 +678,110 @@
 .List;%0A%0A
+import org.apache.hadoop.io.Writable;%0Aimport org.elasticsearch.hadoop.mr.WritableValueWriter;%0A
 import o
@@ -829,16 +829,16 @@
 erator;%0A
-
 import o
@@ -1250,16 +1250,72 @@
 kWriter;
+%0A    private final ValueWriter%3CWritable%3E writableWriter;
 %0A%0A    pu
@@ -1492,16 +1492,85 @@
 Types);%0A
+        writableWriter = new WritableValueWriter(writeUnknownTypes);%0A
     %7D%0A%0A 
@@ -2052,47 +2052,191 @@
     
-if (!jdkWriter.write(tuple.getObject(i)
+Object object = tuple.getObject(i);%0A            if (!jdkWriter.write(object, generator)) %7B%0A                if (!(object instanceof Writable) %7C%7C !writableWriter.write((Writable) object
 , ge
@@ -2259,24 +2259,28 @@
             
+    
 return false
@@ -2281,16 +2281,34 @@
  false;%0A
+                %7D%0A
         

extend cascading value writer to handle Writable types