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

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

    def filterService
    def assetService
    def taskProcedureService

    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.errorMessage = "TaskProcedure ${params.id} could not be deleted"
                redirect(controller:'taskDetailed',
                                action:'show',
                                id:taskInstance.id,
                                params:[showTab:"showProcedureTab"])
            }
        }
        else {
            flash.errorMessage = "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.errorMessage = "TaskProcedure not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            def assemblies = assetService.getAssemblies(taskProcedureInstance.linkedTask.primaryAsset)
            return [ taskProcedureInstance : taskProcedureInstance,
                            assemblies: assemblies ]
        }
    }

    def update = {
        def result = taskProcedureService.update(params)

        if(!result.error) {
            flash.message = g.message(code: "default.update.success", args: ["TaskProcedure", params.id])
            redirect(controller:'taskDetailed',
                            action:'show',
                            id:result.taskProcedureInstance.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
            return
        }

        if(result.error.code == "default.not.found") {
            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
            redirect(action:list)
            return
        }

        if(result.error.code == "default.optimistic.locking.failure") {
            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
            redirect(controller:'taskDetailed',
                            action:'show',
                            id:result.taskProcedureInstance.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
            return
        }

        def assemblies = assetService.getAssemblies(result.taskProcedureInstance.linkedTask.primaryAsset)
        render(view:'edit', model:[taskProcedureInstance: result.taskProcedureInstance,
                                                assemblies: assemblies])
    }

    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)

        // Task already has a taskProcedure.
        if(params.linkedTask.taskProcedure) {
            flash.errorMessage = g.message(code: 'default.optimistic.locking.failure')
            redirect(controller:'taskDetailed',
                            action:'show',
                            id:params.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
            return
        }

        // Task does not have a primaryAsset.
        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

        // Populate a couple of maintenanceActions for the first assembly.
        def assemblies = assetService.getAssemblies(params.linkedTask.primaryAsset)
        if(assemblies) {
            def assembly = assemblies[0]
            def ma = taskProcedureInstance.maintenanceActionLazyList.get(0)
            ma.assetSubItem = assembly
            ma.procedureStepNumber = 10
            ma = taskProcedureInstance.maintenanceActionLazyList.get(1)
            ma.assetSubItem = assembly
            ma.procedureStepNumber = 20
        }

        return ['taskProcedureInstance':taskProcedureInstance, 'assemblies': assemblies]
    }

    def save = {
        def result = taskProcedureService.save(params)

        if(!result.error) {
            flash.message = g.message(code: "default.create.success", args: ["TaskProcedure", result.taskProcedureInstance.id])
            redirect(controller:'taskDetailed',
                            action:'show',
                            id:result.taskProcedureInstance.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
            return
        }

        if(result.error.code == "default.optimistic.locking.failure") {
            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
            redirect(controller:'taskDetailed',
                            action:'show',
                            id:result.taskProcedureInstance.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
            return
        }

        def assemblies = assetService.getAssemblies(result.taskProcedureInstance.linkedTask.primaryAsset)
        render(view:'create', model:[taskProcedureInstance: result.taskProcedureInstance,
                                                    assemblies: assemblies])
    }

}
