/*
 * Copyright 2002-2008 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.springframework.config.java.internal.enhancement;

import java.lang.ref.Reference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;


/** TODO: JAVADOC */
class ThreadLocalUtils {

    static Class<?> CLASS_THREAD_LOCAL_MAP_ENTRY = classForName("java.lang.ThreadLocal$ThreadLocalMap$Entry");

    /**
     * Field {@code Reference.referent}.
     */
    static final Field FIELD_REFERENT = getDeclaredField(Reference.class, "referent");

    static final Field FIELD_VALUE = getDeclaredField(CLASS_THREAD_LOCAL_MAP_ENTRY, "value");

    static Class<?> CLASS_THREAD_LOCAL_MAP = classForName("java.lang.ThreadLocal$ThreadLocalMap");

    static final Method METHOD_REMOVE = getDeclaredMethod(CLASS_THREAD_LOCAL_MAP, "remove", ThreadLocal.class);

    /**
     * Field {@code Thread.threadLocals}.
     */
    static final Field FIELD_THREAD_LOCALS = getDeclaredField(Thread.class, "threadLocals");

    /**
     * Field {@code Thread.inheritableThreadLocals}.
     */
    static final Field FIELD_INHERITABLE_THREAD_LOCALS = getDeclaredField(Thread.class, "inheritableThreadLocals");

    /**
     * Field {@code ThreadLocalMap.table}.
     */
    static final Field FIELD_TABLE = getDeclaredField(CLASS_THREAD_LOCAL_MAP, "table");



    static Field getDeclaredField(Class<?> from, String name) {
        try {
            Field f = from.getDeclaredField(name);
            f.setAccessible(true);
            return f;
        } catch (SecurityException e) {
            throw new RuntimeException(String.format("Unable to access field '%s' on type '%s'.", name, from.getName()), e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(String.format("Field '%s' is not a declared field on type '%s'.", name, from.getName()), e);
        }
    }

    static Method getDeclaredMethod(Class<?> from, String name, Class<?>... parameterTypes) {
        Method m = ReflectionUtils.findMethod(from, name, parameterTypes);
        if (m == null) {
            throw new RuntimeException("Unable to find method '" + name + "' on class '" + from + "' with types '"
                + StringUtils.arrayToCommaDelimitedString(parameterTypes) + "'.");
        }
        ReflectionUtils.makeAccessible(m);
        return m;
    }

    static Class<?> classForName(String name) {
        try {
            return ClassUtils.getDefaultClassLoader().loadClass(name);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Unable to load class '" + name + "'.", e);
        }
    }

}
