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

class InventoryMovementDetailedController extends BaseController {

    def inventoryMovementService

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

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

    def list = {
        flash.message = flash.message
        redirect(controller:"taskDetailed", action:"search")
    }

    def show = {
        def inventoryMovementInstance = InventoryMovement.get( params.id )

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

    def delete = {
        def result = inventoryMovementService.reverseMove(params)

        if(!result.error) {
            flash.message = "InventoryMovement ${params.id} deleted"
            redirect(controller:"taskDetailed", action:"show", id:result.taskId)
        }
        else {
            if(result.inventoryMovementInstance) {
                // For some reason we have to call refresh() here to get a hibernate session
                // and avoid a lazy initialisation error.
                render(view:'show',model:[inventoryMovementInstance:result.inventoryMovementInstance.refresh()])
            }
            else {
                flash.message = "Could not delete inventory movement."
                redirect(controller:"taskDetailed", action:"search")
            }
        }
    }

    def create = {
        if(!params.task?.id) {
            flash.message = "Please select a task, then the Inventory tab."
            redirect(controller:"taskDetailed", action:"search")
        }
        def inventoryMovementInstance = new InventoryMovement()
        inventoryMovementInstance.properties = params
        return ['inventoryMovementInstance':inventoryMovementInstance]
    }

    def save = {
        def result = inventoryMovementService.move(params)

        if(!result.error) {
            flash.message = "Inventory Movement for ${result.inventoryMovementInstance.inventoryItem.name} created."
            redirect(controller:"taskDetailed", action:"show", id: result.taskId)
        }
        else {
            if(result.inventoryMovementInstance) {
                render(view:'create',model:[inventoryMovementInstance:result.inventoryMovementInstance])
            }
            else {
                flash.message = "Could not create inventory movement."
                redirect(controller:"taskDetailed", action:"search", id:result.taskId)
            }

        }
    }

}
