/*
 * 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.
 */

using System;
using System.IO;
using System.Reflection;
using ParquetSharp.External;

namespace ParquetSharp.Hadoop.Util
{
    public class CompatibilityUtil
    {
        // Will be set to true if the implementation of FSDataInputSteam supports
        // the 2.x APIs, in particular reading using a provided ByteBuffer
        private static bool useV21;
        public static readonly V21FileAPI fileAPI;

        public class V21FileAPI
        {
            private readonly MethodInfo PROVIDE_BUF_READ_METHOD;
            private readonly Type FSDataInputStreamCls;

            internal V21FileAPI()
            {
                string PACKAGE = "org.apache.hadoop";
                FSDataInputStreamCls = Class.forName(PACKAGE + ".fs.FSDataInputStream");
                PROVIDE_BUF_READ_METHOD = FSDataInputStreamCls.getMethod("read", typeof(ByteBuffer));
            }
        }

        static CompatibilityUtil()
        {
            // Test to see if a class from the Hadoop 2.x API is available
            bool v21 = true;
            try
            {
                Class.forName("org.apache.hadoop.io.compress.DirectDecompressor");
            }
            catch (ClassNotFoundException cnfe)
            {
                v21 = false;
            }

            useV21 = v21;
            try
            {
                if (v21)
                {
                    fileAPI = new V21FileAPI();
                }
                else {
                    fileAPI = null;
                }

            }
            catch (ReflectiveOperationException e)
            {
                throw new ArgumentException("Error finding appropriate interfaces using reflection.", e);
            }
        }

        private static object invoke(MethodInfo method, string errorMsg, object instance, params object[] args)
        {
            try
            {
                return method.invoke(instance, args);
            }
            catch (MemberAccessException e)
            {
                throw new ArgumentException(errorMsg, e);
            }
            catch (TargetInvocationException e)
            {
                throw new ArgumentException(errorMsg, e);
            }
        }

        public static int getBuf(FSDataInputStream f, ByteBuffer readBuf, int maxSize)
        {
            int res;
            if (useV21)
            {
                try
                {
                    res = (Integer)fileAPI.PROVIDE_BUF_READ_METHOD.invoke(f, readBuf);
                }
                catch (TargetInvocationException e)
                {
                    if (e.InnerException is NotSupportedException)
                    {
                        // the FSDataInputStream docs say specifically that implementations
                        // can choose to throw NotSupportedException, so this should
                        // be a reasonable check to make to see if the interface is
                        // present but not implemented and we should be falling back
                        useV21 = false;
                        return getBuf(f, readBuf, maxSize);
                    }
                    else if (e.InnerException is IOException)
                    {
                        throw e.InnerException;
                    }
                    else {
                        // To handle any cases where a Runtime exception occurs and provide
                        // some additional context information. A stacktrace would just give
                        // a line number, this at least tells them we were using the version
                        // of the read method designed for using a ByteBuffer.
                        throw new IOException("Error reading out of an FSDataInputStream " +
                            "using the Hadoop 2 ByteBuffer based read method.", e.InnerException);
                    }
                }
                catch (MemberAccessException e)
                {
                    // This method is public because it is defined in an interface,
                    // there should be no problems accessing it
                    throw new ShouldNeverHappenException(e);
                }
            }
            else {
                byte[] buf = new byte[maxSize];
                res = f.read(buf);
                readBuf.put(buf, 0, res);
            }
            return res;
        }
    }
}
