package org.arefgard.icerya.container.injection.impl;

import java.lang.annotation.Annotation;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.arefgard.icerya.container.ContainerException;
import org.arefgard.icerya.container.IceryaContainer;
import org.arefgard.icerya.container.def.BeanDef;

public class EJBInjectionStrategy extends SetterInjectionStrategy {

	private static final String PROPERTY_INITIAL_FACTORY = "java.naming.factory.initial";
	private static final String PROPERTY_PROVIDER_URL = "java.naming.provider.url";
	private static final String PROPERTY_SECURITY_PRINCIPAL = "java.naming.security.principal";
	private static final String PROPERTY_SECURITY_CREDENCIALS = "java.naming.security.credentials";
	
	private static Context context = null;
	
	@Override
	protected void generate(BeanDef beanDef) throws ContainerException {
		IceryaContainer container = beanDef.getContainer();
		try {
			if(context == null) {
				Properties prop = new Properties();
				String factory = container.getMetaDefinition(PROPERTY_INITIAL_FACTORY);
				if(factory != null && !factory.equals("")) {
					prop.setProperty(PROPERTY_INITIAL_FACTORY, factory);
				}
				String url = container.getMetaDefinition(PROPERTY_PROVIDER_URL);
				if(url != null && !url.equals("")) {
					prop.setProperty(PROPERTY_PROVIDER_URL, url);
				}
				String principal = container.getMetaDefinition(PROPERTY_SECURITY_PRINCIPAL);
				if(principal != null && !principal.equals("")) {
					prop.setProperty(PROPERTY_SECURITY_PRINCIPAL, principal);
				}
				String credencials = container.getMetaDefinition(PROPERTY_SECURITY_CREDENCIALS);
				if(credencials != null && !credencials.equals("")) {
					prop.setProperty(PROPERTY_SECURITY_CREDENCIALS, credencials);
				}
				if(prop.size() > 0) {
					context = new InitialContext(prop);
				}else {
					context = new InitialContext();
				}
			}
			this.injectObject = context.lookup(beanDef.getJndiName());
		}catch(Exception e) {
			throw new ContainerException(e);
		}
	}

	@Override
	protected void injection(BeanDef beanDef) throws ContainerException {
		super.injection(beanDef);
	}
	
	public static boolean checkEJB(Class cls) {
		Annotation[] annotations = cls.getAnnotations();
		int annotationLen = annotations.length;
		for(int i = 0; i < annotationLen; i++) {
			String name = annotations[i].getClass().getName();
			if("javax.ejb.Stateless".equals(name)) {
				return true;
			}else if("javax.ejb.Stateful".equals(name)) {
				return true;
			}else if("javax.persistence.Entity".equals(name)) {
				return true;
			}
		}
		return false;
	}
	
}
