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

class InventoryItemDetailedController extends BaseController {

    def filterService
    def inventoryItemService
    def inventoryMovementService

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

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

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ inventoryItemInstanceList: InventoryItem.list( params ), inventoryItemInstanceTotal: InventoryItem.count() ]
    }

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

        // Quick Search:
        if(!params.filter) {
            return[ inventoryItemInstanceList: InventoryItem.list( params ), inventoryItemInstanceTotal: InventoryItem.count(), filterParams: params ]
        }
        // filterPane:
        return[ inventoryItemInstanceList: filterService.filter( params, InventoryItem ),
                inventoryItemInstanceTotal: filterService.count( params, InventoryItem ),
                filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params),
                params:params ]
    }

    /**
    * Simply assigns a passed in task id to a session variable and redirects to search.
    */
    def findInventoryItemForMovement = {
        if(!params.task?.id) {
            flash.message = "No task id supplied, please select a task then the inventory tab."
            redirect(controller: "taskDetailed", action: "search")
            return
        }

        session.inventoryMovementTaskId = params.task.id
        flash.message = "Please find and then select the inventory item."
        redirect(action: search)
    }

    def show = {

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

        if(!InventoryItem.exists(params.id)) {
            flash.message = "InventoryItem not found with id ${params.id}"
            redirect(action:search)
            return
        }

        def result = inventoryItemService.prepareShowData(params)

        if(result.error) {
            flash.message = "Could not to prepare the data to show item with id: ${params.id}."
            redirect(action:search)
            return
        }

        def model = [ inventoryItemInstance: result.inventoryItemInstance,
                                inventoryMovementList: result.inventoryMovementList,
                                inventoryMovementListTotal: result.inventoryMovementListTotal,
                                inventoryMovementListMax: result.inventoryMovementListMax,
                                showTab: result.showTab]

        if(session.inventoryMovementTaskId) {
            model.inventoryMovementInstance = new InventoryMovement()
            model.inventoryMovementInstance.task = Task.get(session.inventoryMovementTaskId)
            model.inventoryMovementInstance.quantity = 1
        }

        return model
    }

    def delete = {
        def inventoryItemInstance = InventoryItem.get( params.id )
        if(inventoryItemInstance) {
            try {
                inventoryItemInstance.delete(flush:true)
                flash.message = "InventoryItem ${params.id} deleted"
                redirect(action:search)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "InventoryItem ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "InventoryItem 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 inventoryItemInstance = InventoryItem.get( params.id )

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

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

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

    def save = {
        def inventoryItemInstance = new InventoryItem(params)
        if(!inventoryItemInstance.hasErrors() && inventoryItemInstance.save(flush: true)) {
            flash.message = "InventoryItem ${inventoryItemInstance.id} created"
            redirect(action:show,id:inventoryItemInstance.id)
        }
        else {
            render(view:'create',model:[inventoryItemInstance:inventoryItemInstance])
        }
    }

    /**
    * Handles the use inventory item form submit in the show view.
    */
    def useInventoryItem = {

        params.inventoryMovementType = InventoryMovementType.get(1) // Set type to "Used".
        def result = inventoryMovementService.move(params)

        if(!result.error) {
            flash.message = "Inventory Movement for ${result.inventoryMovementInstance.inventoryItem.name.encodeAsHTML()} created."
            redirect(controller:"taskDetailed", action:"show", id: result.taskId)
        }
        else {
            if(result.inventoryMovementInstance) {
                def p = [:]
                p.id = result.inventoryMovementInstance.inventoryItem?.id
                def r = inventoryItemService.prepareShowData(p)

                def model = [ inventoryItemInstance: r.inventoryItemInstance,
                                        inventoryMovementList: r.inventoryMovementList,
                                        inventoryMovementListTotal: r.inventoryMovementListTotal,
                                        inventoryMovementListMax: r.inventoryMovementListMax,
                                        showTab: r.showTab]

                model.inventoryMovementInstance = result.inventoryMovementInstance

                render(view: 'show', model: model)
            }
            else {
                flash.message = "Could not create inventory movement."
                redirect(action:"search")
            }

        }
    }

}
