/* Copyright 2008 we-lab-doc! (http://www.we-lab-doc.com/)
 *
 * 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 com.we_lab_doc.spacecard.bean;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import groovy.util.ConfigObject;
import org.codehaus.groovy.grails.commons.ApplicationHolder;

import com.we_lab_doc.spacecard.bean.annotation.SpaceCardBean;
import com.we_lab_doc.spacecard.bean.annotation.SpaceCardCustomBean;

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: March 10, 2008
 * 
 */
final public class BeanHelper {
	public static String getCustomBeanName(Class clazz) {
		String name = clazz.getName();
		String role = (String)populatedBeanMap.get(name);
		return role != null ? role : null;
	}
	public static SpaceCardBean getSpaceCardBeanAnnotation(Class<?> clazz) {
		assert clazz != null;
		return (SpaceCardBean)clazz.getAnnotation(SpaceCardBean.class);		
	}
	public static SpaceCardCustomBean getSpaceCardCustomBeanAnnotation(Class<?> clazz) {
		assert clazz != null;
		return (SpaceCardCustomBean)clazz.getAnnotation(SpaceCardCustomBean.class);		
	}	
	//////////////////////////////////////////////////////////
	private static Map populatedBeanMap = null;
	static {
		try {
			populateBeanMap();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			Runtime.getRuntime().exit(-1);
		}
	}	
	private static void populateBeanMap() throws MalformedURLException {
		ConfigObject configObject = ApplicationHolder.getApplication().getConfig();
		Map CustomBeanMap = (Map)((ConfigObject)configObject.getProperty("spacecard")).getProperty("customBeanMap");
		assert CustomBeanMap != null;
		Map<Object, Object> pMap = new HashMap<Object, Object>();
        Iterator it = CustomBeanMap.entrySet().iterator();
        if (it.hasNext()) {
            do {
                Entry ent = (Entry) it.next();
                pMap.put(ent.getValue(), ent.getKey());
            } while (it.hasNext());
        }
        populatedBeanMap = pMap ;
	}	
	
}
