/************************************************
 * Copyright (c) Shen Li. All rights reserved.  *
 * http://joyaop.sourceforge.net                *
 * -------------------------------------------- *
 * Distributable under LGPL license.            *
 * See terms of license at gnu.org.             *
 ************************************************/
package net.sf.joyaop.impl;

import net.sf.cglib.proxy.Callback;
import net.sf.joyaop.framework.Aspect;
import net.sf.joyaop.framework.MixinAspect;
import net.sf.joyaop.framework.AspectizedClass;
import net.sf.joyaop.framework.RuntimeAspect;

import java.util.Collections;

/**
 * @author Shen Li
 */
class MixinCallbackFactory extends CallbackFactory {
    private Callback cachedCallback;
    private MixinAspect aspect;
    private AspectizedClass aspectizedClass;
    private boolean needThreadLocalInvocation;

    public MixinCallbackFactory(AspectizedClass aspectizedClass, MixinAspect aspect) {
        this.aspect = aspect;
        this.aspectizedClass = aspectizedClass;
        needThreadLocalInvocation = needThreadLocalInvocation(aspect.getAspectClass());
        if (!RuntimeAspect.INSTANCE_SCOPE.equals(aspect.getScope())) {
            cachedCallback = new CallbackImpl(
                    Collections.EMPTY_LIST,
                    new RuntimeAspectInstanceFactory(aspectizedClass.getOriginalClass()).getRuntimeAspectInstance(aspect),
                    needThreadLocalInvocation);
        }
    }

    public Callback getCallback(RuntimeAspectInstanceFactory factory) {
        if (cachedCallback == null) {
            return new CallbackImpl(
                    Collections.EMPTY_LIST,
                    new RuntimeAspectInstanceFactory(aspectizedClass.getOriginalClass()).getRuntimeAspectInstance(aspect),
                    needThreadLocalInvocation);
        }
        return cachedCallback;
    }
}