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)

        def taskProcedureInstanceList
        def taskProcedureInstanceTotal
        def filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)

        if(params.filter) {
            taskProcedureInstanceList = filterService.filter( params, TaskProcedure )
            taskProcedureInstanceTotal = filterService.count( params, TaskProcedure )
        }
        else {
            taskProcedureInstanceList = TaskProcedure.list(params)
            taskProcedureInstanceTotal = TaskProcedure.count()
        }

        // filterPane:
        return[ taskProcedureInstanceList: taskProcedureInstanceList,
            taskProcedureInstanceTotal: taskProcedureInstanceTotal,
            filterParams: filterParams,
            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(action:'list')
            return
        }

        def taskProcedureRevision
        if(params.revision?.toInteger())
             taskProcedureRevision = taskProcedureInstance.getRevision( params.revision )
        else
             taskProcedureRevision = taskProcedureInstance.latestRevision

        if(!taskProcedureRevision) {
            flash.errorMessage = "TaskProcedure ${params.id} revision ${params.revision} not found"
            redirect(action:'list')
            return
        }

        return [taskProcedureRevision: taskProcedureRevision]

    }

    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(action:'show', id:result.taskProcedureInstance.id)
            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(action:'show', id:result.taskProcedureInstance.id)
            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.taskProcedureRevision) {
            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(action:'show', id:result.taskProcedureInstance.id)
            return
        }

        // Task already has a taskProcedure.
        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:params.linkedTask.id,
                            params:[showTab:"showProcedureTab"])
            return
        }

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

}
