/* 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.ac.*
import com.we_lab_doc.spacecard.model.*
import com.we_lab_doc.spacecard.utils.*

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: June 19, 2008
 */ 
class FlexUserService   {
	static expose = ['flex-remoting']

	// TODO: AccessControlの仕掛け

	def getUsers() {
		def spaceCardModelProperties = SpaceCardModel.props
		def users = User.findAllByAccountNotEqual(spaceCardModelProperties.supervisorAccount, [sort:"account"])
		users = users.collect {
			[id:it.id, account:it.account, status:it.active? "有効" : "無効", createdDate:it.createdDate]
		}
		return users
	}

	def createUser(def data) {
		def user
		User.withTransaction  { tx ->
			def password = User.encodePassword(data.password)
			data.password = password
			user = User.create(data)
			if(!ModelUtils.save(user))  throw new IllegalStateException("作成に失敗しました");
		}
		return user.id
	}
	
	def getUserById(def userId) {
		User user = User.get(userId)
		if(!user) throw new IllegalStateException("id に対応するユーザが存在しません")
		return  [id:user.id, account:user.account, firstName:user.firstName, lastName:user.lastName, firstNameKana:user.firstNameKana, lastNameKana:user.lastNameKana,
		        description:user.description,email:user.email,
		        status:user.active? "有効" : "無効", createdDate:user.createdDate]
	}
	
	def getUserByAccount(def account) {
		println (account)
		User user = User.findByAccount(account)
		if(!user) throw new IllegalStateException("account に対応するユーザが存在しません")
		return  [id:user.id, account:user.account, firstName:user.firstName, lastName:user.lastName, firstNameKana:user.firstNameKana, lastNameKana:user.lastNameKana,
		        description:user.description,email:user.email,
		        status:user.active? "有効" : "無効", createdDate:user.createdDate]
	}	
	
	def updateUser(def userId, def data) {
		User user = User.get(userId)
		if(!user) throw new IllegalStateException("id に対応するユーザが存在しません")
		if(data?.password.length() > 0 ) {
			def password = User.encodePassword(data.password)
			data.password = password
		} else {
			data.password = user.password
		}
		user.properties = data
		if(!ModelUtils.save(user))  throw new IllegalStateException("更新に失敗しました");
		return user.id			
	}
	
}	