/*
 * 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 static org.springframework.config.java.internal.enhancement.ThreadLocalUtils.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;


/** TODO: JAVADOC */
class ThreadLocalMapEntryData {

    private static final Log log = LogFactory.getLog(ThreadLocalMapEntryData.class);

    final ThreadLocal<?> threadLocal;
    final Thread owningThread;
    final Object owningThreadLocalMap;
    final Object value;

    public ThreadLocalMapEntryData(Thread owningThread, Object owningMap, Object mapEntry) {
        Assert.notNull(owningThread, "owningThread must be non-null");

        Assert.notNull(owningMap, "owningMap must be non-null");
        Assert.isInstanceOf(CLASS_THREAD_LOCAL_MAP, owningMap);

        Assert.notNull(mapEntry, "mapEntry must be non-null");
        Assert.isInstanceOf(CLASS_THREAD_LOCAL_MAP_ENTRY, mapEntry);

        this.owningThread = owningThread;
        this.owningThreadLocalMap = owningMap;

        try {
            this.threadLocal = (ThreadLocal<?>) FIELD_REFERENT.get(mapEntry);
            this.value = FIELD_VALUE.get(mapEntry);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public void removeFromOwningMap() {
        log.debug(String.format("removing threadlocal [%s] having value [%s] from thread %s", threadLocal, value, owningThread));

        try {
            METHOD_REMOVE.invoke(owningThreadLocalMap, threadLocal);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

}
