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

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.arefgard.icerya.container.ContainerException;
import org.arefgard.icerya.container.def.BeanDef;
import org.arefgard.icerya.container.def.ConstructorArgDef;
import org.arefgard.icerya.container.def.ResourceDef;
import org.arefgard.icerya.container.def.ValueResourceDef;
import org.arefgard.icerya.container.util.ReflectionUtil;

public class ConstructorInjectionStrategy extends SetterInjectionStrategy  {

	/** ロガー */
	private static final Log log = LogFactory.getLog(ConstructorInjectionStrategy.class);
	
	@Override
	protected void generate(BeanDef beanDef) throws ContainerException {
		try {
			if(this.injectObject == null) {
				// オブジェクトが存在しない場合
				if(beanDef == null) {
					log.error("Illegal BeanDef.");
					throw new ContainerException("Illegal Argument.");
				}
				String id = beanDef.getBeanId();
				Class cls = null;
				try {
					cls = Class.forName(beanDef.getBeanClass());
				}catch(Exception e) {
					throw new ContainerException("class[" + beanDef.getBeanClass() + "] is not found");
				}
				
				if(log.isDebugEnabled()) {
					log.debug("  id = " + id + ", className = " + cls.getName());
				}
				List<ConstructorArgDef> argsList = beanDef.getConstructorArgs();
				
				Object[] args = new Object[argsList.size()];
				
				for(int i = 0; i < args.length; i++) {
					ResourceDef resourceDef = argsList.get(i).getResourceDef();
					
					if(resourceDef instanceof ValueResourceDef) {
						ValueResourceDef valueDef = (ValueResourceDef)resourceDef;
						args[i] = valueDef.getValue();
					}
				}
				
				this.injectObject = ReflectionUtil.generate(cls, args);
			}
		}catch(Exception e) {
			throw new ContainerException(e);
		}
		
	}
	
	@Override
	protected void injection(BeanDef beanDef) throws ContainerException {
		super.injection(beanDef);
	}
	

}
