/* 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.utils.*
import com.we_lab_doc.spacecard.model.abstracts.SpaceCard
import com.we_lab_doc.spacecard.model.*
import com.we_lab_doc.spacecard.service.SpaceCardModelConfigurer
import com.we_lab_doc.spacecard.service.SpaceCardModelConfigurer.SpaceCardModelProperties
import org.apache.log4j.Logger
import com.we_lab_doc.spacecard.bean.annotation.SpaceCardCustomBean

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: February 24, 2008
 */
@SpaceCardCustomBean
final class DefaultSpaceCardModelConfigurer implements SpaceCardModelConfigurer {
	static log = Logger.getLogger("grails.app.service.${DefaultSpaceCardModelConfigurer.class.getSimpleName()}")
	def spaceCardModelProperties
	def pmtSerialManager
	
	boolean configureIfNeeds() {
		if(pmtSerialManager && pmtSerialManager.initialize())
			return initializeModel()
		log.error("configureIfNeeds; pmtSerialManager(${pmtSerialManager}) initialization failed.")	
		return false
	}
	SpaceCardModelProperties getSpaceCardModelProperties() {
		return spaceCardModelProperties
	}
	///////////////////////////////////////////////////////////
	private boolean initializeModel() {
		SpaceCard.withTransaction { tx ->
			def supervisorCommunity = Organization.getSupervisorCommunity()
			if(supervisorCommunity) return true
			log.info("#### initialize SpaceCard Model")
			supervisorCommunity = Organization.createSupervisorCommunity()
			if(!ModelUtils.saveWithRollback(supervisorCommunity,tx)) return false
			def supervisorRole = Role.getSupervisorRole()
			def supervisor = User.createSupervisor(supervisorRole)
			if(!ModelUtils.saveWithRollback(supervisor,tx)) return false
		}
		return true
	}	
}



