import org.codehaus.groovy.grails.plugins.springsecurity.Secured

class TaskDetailedController extends BaseController {

    def authenticateService
    def dateUtilService
    def taskSearchService
    def filterService

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def index = { redirect(action:search,params:params) }

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100 )
        [ taskInstanceList: Task.list( params ), taskInstanceTotal: Task.count() ]
    }

    def search = {
//         println params
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100 )

        // Search urls:
        if(!params.filter)
        {
            def taskInstanceList = []
            def personInstance = Person.get(authenticateService.userDomain().id)

            if(params.searchMyTodays) {
                taskInstanceList = taskSearchService.getMyTodays(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Today's tasks for ${personInstance.firstName} ${personInstance.lastName}." }
                else { params.message = "No tasks found for today." }
            }
            else if(params.searchInTheLastWeek) {
                taskInstanceList = taskSearchService.getInTheLastWeek(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Tasks with Target Start Date in the last week." }
                else { params.message = "No tasks found for today." }
            }
            else if(params.searchMyInTheLastWeek) {
                taskInstanceList = taskSearchService.getMyInTheLastWeek(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Tasks with Target Start Date in the last week for ${personInstance.firstName} ${personInstance.lastName}." }
                else { params.message = "No tasks found for today." }
            }
            else {
                //Default:
                taskInstanceList = taskSearchService.getTodays(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Today's tasks." }
                else { params.message = "No tasks found for today." }
            }

            return[ taskInstanceList: taskInstanceList, taskInstanceTotal: taskInstanceList.totalCount]
        }
        // filterPane:
        return[ taskInstanceList: filterService.filter( params, Task ),
            taskInstanceTotal: filterService.count( params, Task ),
            filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params),
            params:params ]
    }

    def advancedSearch = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100 )

        if(!params._action_advancedSearch)
        {
            // Default:
            def taskInstanceActivesList = Task.findAllByIsActive(true, params)
            def taskInstanceActivesTotal = Task.countByIsActive(true)
            return [taskInstanceList: taskInstanceActivesList, taskInstanceTotal: taskInstanceActivesTotal]
        }
        render( view:'advancedSearch', 
            model:[ taskInstanceList: filterService.filter( params, Task ), 
            taskInstanceTotal: filterService.count( params, Task ), 
            filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params), 
            params:params ] )
    }
    
//     def searchTodays = {
//         def taskInstanceList = taskSearchService.getTodays(params)
//         
//         if(taskInstanceList.totalCount > 0)
//         {
//             flash.message = "Today's tasks"
//         }
//         else { flash.message = "No tasks found for today" }
//         
//         render( view:'search', 
//             model:[ taskInstanceList: taskInstanceList, 
//             taskInstanceTotal: taskInstanceList.totalCount])
//     }
    
//     def searchMyTodays = {
//         params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
//             
//         def taskInstanceList = Task.createCriteria().list() {
//                 eq("leadPerson", Person.get(authenticateService.userDomain().id))
//                 ge("targetStartDate", dateUtilService.getToday())
//                 eq("isActive", true)
//         }
//             
//         def taskInstanceTotal = Task.createCriteria().count() {
//                 eq("leadPerson", Person.get(authenticateService.userDomain().id))
//                 ge("targetStartDate", dateUtilService.getToday())
//                 eq("isActive", true)
//         }
//         
//         if(taskInstanceTotal > 0)
//         {
//             flash.message = "Today's tasks"
//         }
//         else { flash.message = "No tasks found for today" }
//         
//         render( view:'search', 
//             model:[ taskInstanceList: taskInstanceList, 
//             taskInstanceTotal: taskInstanceTotal])
//     }
    
    def searchInTheLastWeek = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
            
        def taskInstanceList = Task.createCriteria().list() {
                ge("targetStartDate", dateUtilService.getToday()-7)
                eq("isActive", true)
        }
            
        def taskInstanceTotal = Task.createCriteria().count() {
                ge("targetStartDate", dateUtilService.getToday()-7)
                eq("isActive", true)
        }
        
        if(taskInstanceTotal > 0)
        {
            flash.message = "Tasks with target start date in the last week."
        }
        
        else {flash.message = "No tasks found with target start date in the last week." }
        
        render( view:'search', 
            model:[ taskInstanceList: taskInstanceList, 
            taskInstanceTotal: taskInstanceTotal])
    }
    
    def searchMyInTheLastWeek = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
            
        def taskInstanceList = Task.createCriteria().list() {
                eq("leadPerson", Person.get(authenticateService.userDomain().id))
                ge("targetStartDate", dateUtilService.getToday()-7)
                eq("isActive", true)
        }
            
        def taskInstanceTotal = Task.createCriteria().count() {
                eq("leadPerson", Person.get(authenticateService.userDomain().id))
                ge("targetStartDate", dateUtilService.getToday()-7)
                eq("isActive", true)
        }
        
        if(taskInstanceTotal > 0)
        {
            flash.message = "Tasks with target start date in the last week."
        }
        else { flash.message = "No tasks found with target start date in the last week." }
        
        render( view:'search', 
            model:[ taskInstanceList: taskInstanceList, 
            taskInstanceTotal: taskInstanceTotal])
    }

//     def search = {
//         params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
//         
//         if(!params.order) {
//             params.sort = "id"
//             params.order = "desc"
//         }
//         
//         if(params.search == "ShowAll")
//         {
//             def taskInstanceActivesList = Task.findAllByIsActive(true, params)
//             def taskInstanceActivesTotal = Task.countByIsActive(true)
//             return [taskInstanceList: taskInstanceActivesList, taskInstanceTotal: taskInstanceActivesTotal]
//         }
//         if(params.search == "ShowDeleted")
//         {
//             def taskInstanceActivesList = Task.findAllByIsActive(false, params)
//             def taskInstanceActivesTotal = Task.countByIsActive(false)
//             return [taskInstanceList: taskInstanceActivesList, taskInstanceTotal: taskInstanceActivesTotal]
//         }
//         // Default:
//         def taskInstanceActivesList = Task.findAllByIsActive(true, params)
//         def taskInstanceActivesTotal = Task.countByIsActive(true)
//         [taskInstanceList: taskInstanceActivesList, taskInstanceTotal: taskInstanceActivesTotal]
//     }
    
    def searchShowAll = {
        redirect(action:'search', params:[search:"ShowAll"])
    }
    
    def searchShowDeleted = {
        redirect(action:'search', params:[search:"ShowDeleted"])
    }

    def show = {

        // In the case of an actionSubmit button, rewrite action name from 'index'.
        if(params._action_Show)
        { params.action='show' }

        def taskInstance = Task.get( params.id )

        if(!taskInstance) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action:search)
        }
        else {
			params.max = 10
			params.order = "desc"
			params.sort = "id"
			
			def entryWorkDoneList = Entry.withCriteria {
																def entryType = EntryType.findByName("WorkDone")
																eq("entryType", entryType)
																eq("task", taskInstance)
														}
			
			def entryFaultList = Entry.withCriteria {
																def entryType = EntryType.findByName("Fault")
																eq("entryType", entryType)
																eq("task", taskInstance)
														}

			def subTaskInstanceList = Task.findAllByParentTask(taskInstance, params)
			def subTaskInstanceTotal = Task.countByParentTask(taskInstance)					
            def showTaskTab = new String("true")

            def taskProcedureInstance = TaskProcedure.get(taskInstance.taskProcedure?.id)
            def taskProcedureExits = new Boolean("true")
            if(!taskProcedureInstance) {
                taskProcedureExits = false
            }
// 			else {
				params.order = "asc"
				params.sort = "procedureStepNumber"
				def maintenanceActionList = MaintenanceAction.findAllByTaskProcedure(taskProcedureInstance, params)
// 			}
						
            def taskRecurringScheduleInstance = TaskRecurringSchedule.get(taskInstance.taskRecurringSchedule?.id)
            def taskRecurringScheduleExits= new Boolean("true")
			if(!taskRecurringScheduleInstance) {
                taskRecurringScheduleExits = false
            }
			
            return [ taskInstance: taskInstance,
							entryWorkDoneList: entryWorkDoneList,
	   						entryFaultList: entryFaultList,
                            taskProcedureInstance: taskProcedureInstance,
                            taskProcedureExits: taskProcedureExits,
                            showTaskTab: showTaskTab,
							subTaskInstanceList: subTaskInstanceList,
	   						subTaskInstanceTotal: subTaskInstanceTotal,
		  					subTaskInstanceMax: params.max,
		 					maintenanceActionList: maintenanceActionList,
							taskRecurringScheduleInstance: taskRecurringScheduleInstance,
	   						taskRecurringScheduleExits: taskRecurringScheduleExits] 
        }
    }

    def delete = {
        def taskInstance = Task.get( params.id )
        if(taskInstance) {
            try {
                taskInstance.isActive = false
                flash.message = "Task ${params.id} has been set to inactive."
                redirect(action:search)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Task ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Task not found with id ${params.id}"
            redirect(action:search)
        }
    }

    def edit = {

        // In the case of an actionSubmit button, rewrite action name from 'index'.
        if(params._action_Edit)
        { params.action='edit' }
        
        def taskInstance = Task.get( params.id )

        if(!taskInstance) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action:search)
        }
        else {
            def criteria = taskInstance.createCriteria()
            def result = criteria {
                and {
                    notEqual('id', taskInstance.id)
                    }
            }
            return [ taskInstance : taskInstance, possibleParentList: result ]
        }
    }

    def update = {
        def taskInstance = Task.get( params.id )
        if(taskInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(taskInstance.version > version) {
                    
                    taskInstance.errors.rejectValue("version", "task.optimistic.locking.failure", "Another user has updated this Task while you were editing.")
                    render(view:'edit',model:[taskInstance:taskInstance])
                    return
                }
            }
            taskInstance.properties = params
            if(!taskInstance.hasErrors() && taskInstance.save()) {
                flash.message = "Task ${params.id} updated"
                redirect(action:show,id:taskInstance.id)
            }
            else {
                render(view:'edit',model:[taskInstance:taskInstance])
            }
        }
        else {
            flash.message = "Task not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def taskInstance = new Task()
        taskInstance.properties = params
        return ['taskInstance':taskInstance]
    }

    def save = {
        def taskInstance = new Task(params)
        if(!taskInstance.hasErrors() && taskInstance.save()) {
            flash.message = "Task ${taskInstance.id} created"
            redirect(action:show,id:taskInstance.id)
        }
        else {
            render(view:'create',model:[taskInstance:taskInstance])
        }
    }
	
	def listSubTasks = {
		def parentTaskInstance = Task.get(params.id)
				
        if(!parentTaskInstance) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action:search)
        }
        else {
		params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
		def subTaskInstanceList = Task.findAllByParentTask(parentTaskInstance, params)
		def subTaskInstanceTotal = Task.countByParentTask(parentTaskInstance)
				
        [ taskInstanceList: subTaskInstanceList,
			taskInstanceTotal:  subTaskInstanceTotal,
   			parentTaskInstance: parentTaskInstance]
		}
	}
        
}
