/* 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.
 */
import com.we_lab_doc.spacecard.bean.*
import org.apache.log4j.Logger

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: March 7, 2008
 */
class SpaceCardBeansGrailsPlugin {
    static log = Logger.getLogger("grails.app.plugins.SpaceCardBeans")
	def artefacts = [ com.we_lab_doc.spacecard.bean.SpaceCardBeanClassArtefactHandler ]
	def version = "0.1"
	def author = "Shigeru GOUGI"
    def watchedResources = [ "file:./grails-app/beans/**/*.groovy",
                             "file:./plugins/*/grails-app/beans/**/*.groovy" ]
	def doWithSpring = {
		application.spaceCardBeanClasses.each { beanClass ->
			def scope = beanClass.scope
			def beanName = beanClass.propertyName			
			"${beanName}"(beanClass.getClazz()) { bean ->
				bean.autowire =  true
				bean.scope = scope
			}
            log.info("doWithSpring; ${beanName}, scope = ${scope}")
		}
	}
	def onChange = { event ->	
		if(event.source) {
			def beanClass = application.addArtefact(SpaceCardBeanClassArtefactHandler.TYPE, event.source)
			if(beanClass) {
				def beanName = beanClass.propertyName
	            def scope = beanClass.scope	            
				def beans = beans {
					"$beanName"(beanClass.getClazz()) { bean ->
						bean.autowire =  true
                        if(scope) {
                            bean.scope = scope
                        }
					}					
				}
	            beans.registerBeans(event.ctx)
	            log.info("onChange; ${beanName}, scope= ${scope}")
			}
		 }
	} 

}