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

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: March 20, 2008
 */
@SpaceCardBean(scope="singleton")
class SpaceCardPluginManager {
	 static log = Logger.getLogger("grails.app.plugins.SpaceCardPluginManager")
	 def viewMap = [:]
	 
	 def initialize() {
		 def plugins = PluginUtils.allPlugins
		 for (plugin in plugins ) {
			 def pluginInstance = plugin.instance
			 if(hasField(pluginInstance.class, "doWithSpaceCard")) {
				 try {
					 def conf = new SpaceCardPluginConfiguration()
					 pluginInstance.doWithSpaceCard(conf)
					 for ( c in conf.viewConfigurations ) {
						 if (! viewMap[c.extensionPoint]) {
							 viewMap[c.extensionPoint] = []
						 }
						 viewMap[c.extensionPoint] << [title:c.title, callbackUrl:c.callbackUrl]
					 }
				 } catch (e) {
					 log.error("SpaceCardPluginManager#initialize[doWithSpaceCard];${pluginInstance.class.name}", e)
				 }
			 }
		 }
		 return true
	 }
	 Collection getViews(String extensionPoint) {
		 def views = viewMap[extensionPoint]
		 println "getViews: ${views}"
		 return  views ? views : [] 
	 }
	 ////
	 private boolean hasField(Class clazz, String fieldName) {
		 try {
			 if(clazz.getDeclaredField(fieldName) != null)
				 return true
		 } catch(e) { /* nop */ }
		 return false		 
	 }
}

class SpaceCardPluginConfiguration {
	static log = Logger.getLogger("grails.app.plugins.SpaceCardPluginManager")
	
	def viewConfigurations = []
	def registerView(def config) {
		if(config == null) return
		if( config.extensionPoint 
			 && (config.callbackUrl 
					 && ((config.callbackUrl instanceof String || config.callbackUrl instanceof GString)   
							 || (config.callbackUrl instanceof Map && config.callbackUrl.controller ))) 
			 && config.title) {
			viewConfigurations << config
		} else {
			log.error("SpaceCardPluginConfiguration#registerView; unexpected format ${config}")
		}
	}
}

