/* 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 04, 2008
 */ 
class FlexSuperviseService   {
	static expose = ['flex-remoting']

	// TODO: AccessControlの仕掛け
	
	def getRootOrganizations() {
		def list = Organization.findAllByIsSupervisorCommunityNotEqual(true, [sort:"name", order:"desc"])

		def orgs = list.collect { 
			[id:it.id, name:it.name, createdDate:it.createdDate, status:it.active? "有効" : "無効", description:it.description, isSupervisorCommunity:it.isSupervisorCommunity()]
		}

		//def orgs = list
		/**
		 * failed to lazily initialize a collection of role: com.we_lab_doc.spacecard.model.Organization.organizationWorkspaces, no session or session was closed
		 */
		return orgs
	}
	
	def getAdmins(def orgId) {
		Organization org = Organization.get(orgId)
		if(!org) throw new IllegalStateException("id に対応する組織が存在しません")
		def admins = org.getAdmins(true, null)
		admins = admins.collect {
			[id:it.id, account:it.account, status:it.active? "有効" : "無効"]
		}
		return admins
	}
	
	def updateOrganization(def data) {
		Organization org = Organization.get(data.id)
		if(!org) throw new IllegalStateException("id に対応する組織が存在しません")
		def active = data.status == "有効" ? true : false
		data.active = active
		org.properties = data
		if(!ModelUtils.save(org)) {
			throw new IllegalStateException("更新に失敗しました")
		}
		return data.id
	}
	
	def createCompany(def data) {
		def org = Organization.createCompany(data)
		if(!ModelUtils.save(org))  throw new IllegalStateException();
		return
	}
	
	def addAdmin(def orgId, def userId) {
		Organization org = Organization.get(orgId)
		if(!org) throw new IllegalStateException("id に対応する組織が存在しません")
		User user = User.get(userId)
		if(!user) throw new IllegalStateException("id に対応するユーザが存在しません")
		org.addAdmin(user)
		if(!ModelUtils.save(org))  throw new IllegalStateException("更新に失敗しました");
		return
	}
	
	def rejectAdmin(def orgId, def userId) {
		Organization org = Organization.get(orgId)
		if(!org) throw new IllegalStateException("id に対応する組織が存在しません")
		User user = User.get(userId)
		if(!user) throw new IllegalStateException("id に対応するユーザが存在しません")
		org.removeAdmin(user)
		if(!ModelUtils.save(org))  throw new IllegalStateException("更新に失敗しました");
		return
	}

	
}	