/*
 * 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 test.feature.aop;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

import org.junit.Test;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;

import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.context.JavaConfigApplicationContext;

import test.common.beans.ITestBean;
import test.common.beans.TestBean;

import java.lang.reflect.Method;


/** TODO: JAVADOC */
public class ProgrammaticProxyCreationTests {

    @Test
    public void testProgrammaticProxyCreation() {
        JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ProxyConfiguration.class);

        ITestBean proxy = ctx.getBean(ITestBean.class, "proxied");
        assertSame(proxy, ctx.getBean("proxied"));
        ProxyConfiguration.count = 0;
        String name = "Shane Warne";
        proxy.setName(name);
        assertEquals(1, ProxyConfiguration.count);
        assertEquals(name, proxy.getName());
        assertEquals(2, ProxyConfiguration.count);
    }

    @Configuration
    public static class ProxyConfiguration {
        public static int count;

        @Bean
        public ITestBean proxied() {
            TestBean tb = new TestBean();
            ProxyFactory pf = new ProxyFactory(tb);
            pf.addAdvice(new MethodBeforeAdvice() {
                    public void before(Method method, Object[] args, Object target) throws Throwable { ++count; }
                });
            return (ITestBean) pf.getProxy();
        }
    }

}
