package com.rjconsultores.ventaboletos.web.utilerias;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.lang.reflect.Field;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.GenericForwardComposer;
/*
 *
 * link http://zkforge.svn.sourceforge.net/viewvc/zkforge/trunk/zktodo2/src/main/java/org/zkforge/zktodo2/GenericSpringComposer.java?revision=926&view=markup
 */

public class GenericSpringComposer extends GenericForwardComposer {

    private static final long serialVersionUID = -8554216461300908912L;
    private ServletContext servletContext = null;

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        this.servletContext = (ServletContext) comp.getDesktop().getWebApp().getNativeContext();
        this.wireBeans();
    }

    @Override
    public void didActivate(Component component) {
        System.out.println("jfjfjfjfjfjf");
        super.didActivate(component);
        try {
            this.wireBeans();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void wireBeans() throws IllegalArgumentException, IllegalAccessException {
        System.out.println("dffff wireBeans");
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.servletContext);
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field f : fields) {
            System.out.println("asdfasdfa " + f.getName());
            Resource annotation = f.getAnnotation(Resource.class);
            if (annotation != null) {
                f.setAccessible(true); // Make private fields accessible.
                Object bean = ctx.getBean(annotation.name());
                f.set(this, bean);
            }

        }
    }
}
