/* 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.model.abstracts

import com.we_lab_doc.spacecard.model.*
import com.we_lab_doc.spacecard.utils.*

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: February 13, 2008
 */ 
/* abstract */ class Workspace extends WorkCard {
	Collection getAllTasks(Map paginateParams) {
		return _getTasks( null, paginateParams )
	}	
	Collection getOpenTasks(Map paginateParams) {
		return _getTasks( Boolean.FALSE, paginateParams )
	}	
	Collection getClosedTasks(Map paginateParams) {
		return _getTasks( Boolean.TRUE, paginateParams )
	}
	int countOfAllTasks() {
		return _countOfTasks(null)
	}	
	int countOfOpenTasks() {
		return _countOfTasks(Boolean.FALSE)
	}
	int countOfClosedTasks() {
		return _countOfTasks(Boolean.TRUE)
	}
	////
	private int _countOfTasks(Boolean closed) {
		def qs = _getTasksQS(closed)
		Integer[] counts = SpaceCardModel.executeQuery(
				"select count(t) from Task as t ${qs}", [workspace:this]
			)
		return counts[0].intValue()		
	}
	private Collection _getTasks(Boolean closed, Map paginateParams) {
		def qs = _getTasksQS(closed)
		Map sParams = PaginateUtils.makeSelectParams(paginateParams, [workspace:this])
		return Tasks.select("${qs} ${sParams.orderByClause}", sParams.args)
	}
	private String _getTasksQS(Boolean closed) {
			def checkClosed = ""
		if(closed != null) {
			if(closed.booleanValue())
				checkClosed = "and t.closedDate!=null"
			else
				checkClosed = "and t.closedDate=null"				
		}
		return "where t.workspace=:workspace ${checkClosed}"
	}	
	////
	boolean remove() {
		for(t in ModelUtils.cloneCollection(this.tasks)) {
			if(! t.remove()) return false
		}
		return super.remove()
	}
	boolean close() {
		def user = SpaceCardModel.accessControlService.getLoggedInUser()		
		assert user != null		
		for(t in this.tasks) {
			t.close()
		}
		this.closer = user
		return ModelUtils.save(this)
	}
	/////////////////////////////////////////////
	static transients  = []
	static hasMany     = [tasks:Task]
	static constraints = {
	}
}

