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

@Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager'])
class TaskProcedureDetailedController extends BaseController {

    def filterService
    def authService

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

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

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)

        if(!params.filter)
        { return [taskProcedureInstanceList: TaskProcedure.list(params), taskProcedureInstanceTotal: TaskProcedure.count()] }

        // filterPane:
        return[ taskProcedureInstanceList: filterService.filter( params, TaskProcedure ),
            taskProcedureInstanceTotal: filterService.count( params, TaskProcedure ),
            filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params),
            params:params ]
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def search = {
        redirect(action:list)
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def show = {

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

        def taskProcedureInstance = TaskProcedure.get( params.id )

        if(!taskProcedureInstance) {
            flash.errorMessage = "TaskProcedure not found with id ${params.id}"
            redirect(controller:'taskDetailed', action:'search')
            return
        }

        redirect(controller:'taskDetailed',
                        action:'show',
                        id:taskProcedureInstance.linkedTask?.id,
                        params:[showTab:"showProcedureTab"])
    }

    def delete = {
        def taskProcedureInstance = TaskProcedure.get( params.id )
        if(taskProcedureInstance) {
            def taskInstance = taskProcedureInstance.linkedTask
            try {
                taskProcedureInstance.tasks.each {
                    it.taskProcedure = null
                }
                taskProcedureInstance.delete(flush:true)
                flash.message = "TaskProcedure ${params.id} deleted"
                redirect(controller:'taskDetailed',
                                action:'show',
                                id:taskInstance.id,
                                params:[showTab:"showProcedureTab"])
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "TaskProcedure ${params.id} could not be deleted"
                redirect(controller:'taskDetailed',
                                action:'show',
                                id:taskInstance.id,
                                params:[showTab:"showProcedureTab"])
            }
        }
        else {
            flash.message = "TaskProcedure not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {

        // In the case of an actionSubmit button, rewrite action name from 'index'.
        if(params._action_Edit)
            params.action='edit'

        def taskProcedureInstance = TaskProcedure.get( params.id )

        if(!taskProcedureInstance) {
            flash.message = "TaskProcedure not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ taskProcedureInstance : taskProcedureInstance ]
        }
    }

    def update = {
        def taskProcedureInstance = TaskProcedure.get( params.id )
        if(taskProcedureInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(taskProcedureInstance.version > version) {

                    taskProcedureInstance.errors.rejectValue("version", "default.optimistic.locking.failure")
                    render(view:'edit',model:[taskProcedureInstance:taskProcedureInstance])
                    return
                }
            }
            taskProcedureInstance.properties = params
            taskProcedureInstance.lastUpdatedBy = authService.currentUser
            taskProcedureInstance.lastUpdated = new Date() // Required to trigger version increment.

            // Gaps in the html index's can be created by adding 2 items and removing the first one.
            // This creates a gap at the missing index where LazyList will return a null.
            def nullMaintenanceActions = taskProcedureInstance.maintenanceActions.findAll {!it}
            if (nullMaintenanceActions) {
                taskProcedureInstance.maintenanceActions.removeAll(nullMaintenanceActions)
            }

            // Save for restoration if validation fails.
            def savedMaintenanceActions = new ArrayList(taskProcedureInstance.maintenanceActions)

            // Remove toBeDeleted before validation.
            def toBeDeleted = taskProcedureInstance.maintenanceActions.findAll {it.toBeDeleted}
            if (toBeDeleted) {
                taskProcedureInstance.maintenanceActions.removeAll(toBeDeleted)
            }

            if(!taskProcedureInstance.hasErrors() && taskProcedureInstance.save(flush: true)) {
                flash.message = "TaskProcedure ${params.id} updated"
                redirect(controller:'taskDetailed',
                                action:'show',
                                id:taskProcedureInstance.linkedTask.id,
                                params:[showTab:"showProcedureTab"])
            }
            else {
                // Restore the saved items, some of which contain toBeDeleted flags but
                // have not been deleted yet since validation failed.
                // The toBeDeleted items are hidden in the view.
                taskProcedureInstance.maintenanceActions = savedMaintenanceActions
                // Populate maintenanceAction errors for display.
                taskProcedureInstance.maintenanceActions.each { it.validate() }
                render(view:'edit',model:[taskProcedureInstance:taskProcedureInstance])
            }
        }
        else {
            flash.message = "TaskProcedure not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {

        if(!params.taskInstance?.id) {
            flash.errorMessage = "Please select or create a task, then go to the Procedure tab."
            redirect(controller:"taskDetailed", action:"search")
            return
        }

        params.linkedTask = Task.get(params.taskInstance.id)

        if(!params.linkedTask?.primaryAsset) {
            flash.errorMessage = "Please set a Primary Asset first, then go to the Procedure tab."
            redirect(controller:"taskDetailed", action:"show", id:params.linkedTask?.id)
            return
        }

        def taskProcedureInstance = new TaskProcedure()
        taskProcedureInstance.properties = params
        return ['taskProcedureInstance':taskProcedureInstance]
    }

    def save = {
        def taskProcedureInstance = new TaskProcedure(params)
        taskProcedureInstance.createdBy = authService.currentUser
        taskProcedureInstance.lastUpdatedBy = authService.currentUser
        def taskInstance = Task.get(params.linkedTask.id)

        // Gaps in the html index's can be created by adding 2 items and removing the first one.
        // This creates a gap at the missing index where LazyList will return a null.
        def nullMaintenanceActions = taskProcedureInstance.maintenanceActions.findAll {!it}
        if (nullMaintenanceActions) {
            taskProcedureInstance.maintenanceActions.removeAll(nullMaintenanceActions)
        }

        if(!taskProcedureInstance.hasErrors() && taskProcedureInstance.save(flush: true)) {
             // Also sets: taskInstance.taskProcedure = taskProcedureInstance
            taskProcedureInstance.addToTasks(taskInstance)
            flash.message = "TaskProcedure ${taskProcedureInstance.id} created."
            redirect(controller:'taskDetailed',
                            action:'show',
                            id:taskProcedureInstance.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
        }
        else {
            // Populate maintenanceAction errors for display.
            taskProcedureInstance.maintenanceActions.each { it.validate() }
            render(view:'create',model:[taskProcedureInstance:taskProcedureInstance])
        }
    }

}
