/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 hivemall.ftvec.scaling;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.*;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.io.Text;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A wrapper of [[hivemall.ftvec.scaling.L2NormalizationUDF]].
 *
 * NOTE: This is needed to avoid the issue of Spark reflection.
 * That is, spark-1.3 cannot handle List<> as a return type in Hive UDF.
 * The type must be passed via ObjectInspector.
 * This issues has been reported in SPARK-6747, so a future
 * release of Spark makes the wrapper obsolete.
 */
public class L2NormalizationUDFWrapper extends GenericUDF {
    private L2NormalizationUDF udf = new L2NormalizationUDF();

    private List<Text> retValue = new ArrayList<Text>();
    private ListObjectInspector argumentOIs = null;

    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        if(arguments.length != 1) {
            throw new UDFArgumentLengthException(
                    "normalize() has an only single argument.");
        }

        switch(arguments[0].getCategory()) {
            case LIST:
                ObjectInspector elmOI = ((ListObjectInspector) arguments[0]).getListElementObjectInspector();
                if(elmOI.getCategory().equals(Category.PRIMITIVE)) {
                    if (((PrimitiveObjectInspector) elmOI).getPrimitiveCategory()
                            == PrimitiveCategory.STRING) {
                        break;
                    }
                }
            default:
                throw new UDFArgumentTypeException(0,
                    "normalize() must have List[String] as an argument, but "
                        + arguments[0].getTypeName() + " was found.");
        }

        argumentOIs = (ListObjectInspector) arguments[0];

        ObjectInspector listElemOI = argumentOIs.getListElementObjectInspector();
        ObjectInspector returnElemOI = ObjectInspectorUtils.getStandardObjectInspector(listElemOI);

        return ObjectInspectorFactory.getStandardListObjectInspector(returnElemOI);
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        assert(arguments.length == 1);
        final Object arrayObject = arguments[0].get();
        final ListObjectInspector arrayOI = (ListObjectInspector) argumentOIs;
        /**
         * TODO: Why not List<String> but List<Text>?
         */
        @SuppressWarnings("unchecked")
        final List<String> arg0 = (List<String>) arrayOI.getList(arrayObject);
        List<Text> input = new ArrayList<Text>();
        for (String s : arg0) {
            input.add(new Text(s));
        }
        retValue = udf.evaluate(new ArrayList<Text>(input));
        return retValue;
    }

    @Override
    public String getDisplayString(String[] children) {
        return "normalize(" + Arrays.toString(children) + ")";
    }
}

@@ -1356,32 +1356,318 @@
 mitiveCategory;%0A
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;%0Aimport org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.ObjectInspectorOptions;%0Aimport org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;%0A
 import org.apach
@@ -2261,24 +2261,34 @@
     private 
+transient 
 List%3CText%3E r
@@ -2336,39 +2336,38 @@
 ate 
-ListObjectInspector argumentOIs
+transient Converter toListText
  = n
@@ -3351,44 +3351,414 @@
     
-argumentOIs = (ListObjectInspector) 
+// Create a ObjectInspector converter for arguments%0A        ObjectInspector outputElemOI =%0A                ObjectInspectorFactory.getReflectionObjectInspector(%0A                        Text.class, ObjectInspectorOptions.JAVA);%0A        ObjectInspector outputOI =%0A                ObjectInspectorFactory.getStandardListObjectInspector(outputElemOI);%0A        toListText = ObjectInspectorConverters.getConverter(
 argu
@@ -3765,16 +3765,27 @@
 ments%5B0%5D
+, outputOI)
 ;%0A%0A     
@@ -3820,34 +3820,50 @@
 I = 
-argumentOIs.getListElement
+PrimitiveObjectInspectorFactory.javaString
 Obje
@@ -3865,34 +3865,32 @@
 gObjectInspector
-()
 ;%0A        Object
@@ -3971,25 +3971,24 @@
 istElemOI);%0A
-%0A
         retu
@@ -4209,458 +4209,125 @@
     
-final Object arrayObject = arguments%5B0%5D.get();%0A        final ListObjectInspector arrayOI = (ListObjectInspector) argumentOIs;%0A        /**%0A         * TODO: Why not List%3CString%3E but List%3CText%3E?%0A         */%0A        @SuppressWarnings(%22unchecked%22)%0A        final List%3CString%3E arg0 = (List%3CString%3E) arrayOI.getList(arrayObject);%0A        List%3CText%3E input = new Array
+@SuppressWarnings(%22unchecked%22)%0A        final List%3CText%3E input = (List%3CText%3E) to
 List
-%3C
 Text
-%3E();%0A        for (String s : arg0) %7B%0A            input.add(new Tex
+.convert(arguments%5B0%5D.ge
 t(
-s
 ));%0A
-        %7D%0A
     
@@ -4358,35 +4358,14 @@
 ate(
-new ArrayList%3CText%3E(
 input)
-)
 ;%0A  

Modify codes to handle ObjectInspector in L2NormalizationUDFWrapper