package skadistats.clarity.decoder;

import com.google.protobuf.ByteString;
import com.rits.cloning.Cloner;
import skadistats.clarity.decoder.unpacker.Unpacker;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Util {

    public static int calcBitsNeededFor(long x) {
        if (x == 0) return (0);
        int n = 32;
        if (x <= 0x0000FFFF) {
            n = n - 16; x = x << 16;
        }
        if (x <= 0x00FFFFFF) {
            n = n - 8; x = x << 8;
        }
        if (x <= 0x0FFFFFFF) {
            n = n - 4; x = x << 4;
        }
        if (x <= 0x3FFFFFFF) {
            n = n - 2; x = x << 2;
        }
        if (x <= 0x7FFFFFFF) {
            n = n - 1;
        }
        return n;
    }

    public static String convertByteString(ByteString s, String charsetName) {
        try {
            return s.toString(charsetName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private static final Cloner CLONER = new Cloner();

    public static Object[] clone(Object[] src) {
        return CLONER.deepClone(src);
    }

    public static String arrayIdxToString(int idx) {
        return String.format("%04d", idx);
    }

    public static <T> Class<T> valueClassForUnpacker(Unpacker<T> unpacker) {
        try {
            ParameterizedType interfaceType = (ParameterizedType) unpacker.getClass().getGenericInterfaces()[0];
            Type valueType = interfaceType.getActualTypeArguments()[0];
            return (Class<T>) Class.forName(valueType.getTypeName());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}

@@ -255,40 +255,8 @@
 pe;%0D
-%0Aimport java.lang.reflect.Type;%0D
 %0A%0D%0Ap
@@ -1392,35 +1392,16 @@
 ker) %7B%0D%0A
-        try %7B%0D%0A    
         
@@ -1514,29 +1514,25 @@
     
-    Type valueType = 
+return (Class%3CT%3E)
 inte
@@ -1575,180 +1575,8 @@
 %5D;%0D%0A
-            return (Class%3CT%3E) Class.forName(valueType.getTypeName());%0D%0A        %7D catch (ClassNotFoundException e) %7B%0D%0A            throw new RuntimeException(e);%0D%0A        %7D%0D%0A
     

make compatible with JDK7 (thx decoud)