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

@Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager'])
class InventoryItemDetailedController extends BaseController {

    def filterService
    def exportService
    def inventoryCsvService
    def inventoryItemService
    def inventoryMovementService

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

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    def index = { redirect(action:search, params:params) }

    /**
    * Set session.inventoryItemSearchParamsMax
    */
    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    def setSearchParamsMax = {
        def max = 1000
        if(params.newMax.isInteger()) {
            def i = params.newMax.toInteger()
            if(i > 0 && i <= max)
                session.inventoryItemSearchParamsMax = params.newMax
            if(i > max)
                session.inventoryItemSearchParamsMax = max
        }
        forward(action: 'search', params: params)
    }

    /**
    * Disaply the import view.
    */
    def importInventory = {
    }

    /**
    * Handle the import save.
    */
    def importInventorySave = {
        def result = inventoryCsvService.importInventory(request)

        if(!result.error) {
            flash.message = g.message(code: "inventory.import.success")
            redirect(action:search)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action: importInventory)
    }

    /**
    * Export a csv template.
    * NOTE: IE has a 'validating' bug in dev mode that causes the export to take a long time!
    * This does not appear to be a problem once deployed to Tomcat.
    */
    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    def exportInventoryTemplate = {
        response.contentType = ConfigurationHolder.config.grails.mime.types["csv"]
        response.setHeader("Content-disposition", "attachment; filename=InventoryTemplate.csv")
        def s = inventoryCsvService.buildInventoryTemplate()
        render s
    }

    /**
    * Export a csv test file.
    */
    def exportInventoryExample = {
        response.contentType = ConfigurationHolder.config.grails.mime.types["csv"]
        response.setHeader("Content-disposition", "attachment; filename=InventoryExample.csv")
        def s = inventoryCsvService.buildInventoryExample()
        render s
    }

    /**
    * Export the entire inventory as a csv file.
    */
    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    def exportInventory = {

        def inventoryItemList = InventoryItem.list()

        response.contentType = ConfigurationHolder.config.grails.mime.types["csv"]
        response.setHeader("Content-disposition", "attachment; filename=Inventory.csv")
        def s = inventoryCsvService.buildInventory(inventoryItemList)
        render s
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    def search = {

        if(session.inventoryItemSearchParamsMax)
            params.max = session.inventoryItemSearchParamsMax

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

        def inventoryItemInstanceList = []
        def inventoryItemInstanceTotal
        def filterParams = [:]

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

        // export plugin:
        if(params?.format && params.format != "html") {

            def dateFmt = { date ->
                formatDate(format: "EEE, dd-MMM-yyyy", date: date)
            }
            String title = "Inventory List."

            response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=Inventory.${params.extension}")
            List fields = ["name",
                                "description",
                                "unitsInStock",
                                "unitOfMeasure",
                                "inventoryLocation",
                                "inventoryLocation.inventoryStore"]
            Map labels = ["name": "Name",
                                "description": "Description",
                                "unitsInStock":"In Stock",
                                "unitOfMeasure": "UOM",
                                "inventoryLocation": "Location",
                                "inventoryLocation.inventoryStore": "Store"]

            Map formatters = [:]
            Map parameters = [title: title, separator: ","]

            exportService.export(params.format,
                                                response.outputStream,
                                                inventoryItemInstanceList.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) },
                                                fields,
                                                labels,
                                                formatters,
                                                parameters)
        }

        // Add some basic params to filterParams.
        filterParams.max = params.max
        filterParams.offset = params.offset?.toInteger() ?: 0
        filterParams.sort = params.sort ?: "id"
        filterParams.order = params.order ?: "desc"

        return[ inventoryItemInstanceList: inventoryItemInstanceList,
                inventoryItemInstanceTotal: inventoryItemInstanceTotal,
                filterParams: filterParams ]
    } // end search()

    /**
    * Simply assigns a passed in task id to a session variable and redirects to search.
    */
    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    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)
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    def show = {

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

        def result = inventoryItemService.show(params)

        if(!result.error) {

            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
            }

            // Success.
            return model
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action:search)
        return
    }

    def delete = {
        def result = inventoryItemService.delete(params)

        if(!result.error) {
            flash.message = g.message(code: "default.delete.success", args: ["InventoryItem", params.id])
            redirect(action:search)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)

        if(result.error.code == "default.not.found") {
            redirect(action:search)
            return
        }

        redirect(action:show, id: params.id)
    }

    def edit = {

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

        def result = inventoryItemService.edit(params)

        if(!result.error) {
            def possibleAlternateItems = inventoryItemService.getPossibleAlternateItems(result.inventoryItemInstance)
            return [ inventoryItemInstance : result.inventoryItemInstance, possibleAlternateItems: possibleAlternateItems]
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action:search)
    }

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

        if(!result.error) {
            flash.message = g.message(code: "default.update.success", args: ["InventoryItem", params.id])
            redirect(action:show, id: params.id)
            return
        }

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

        def possibleAlternateItems = inventoryItemService.getPossibleAlternateItems(result.inventoryItemInstance)
        render(view:'edit', model:[inventoryItemInstance: result.inventoryItemInstance.attach(), possibleAlternateItems: possibleAlternateItems])
    }

    def create = {
        def result = inventoryItemService.create(params)

        if(!result.error)
            return [inventoryItemInstance: result.inventoryItemInstance]

        //flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action: search)
    }

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

        if(!result.error) {
            flash.message = g.message(code: "default.create.success", args: ["InventoryItem", result.inventoryItemInstance.id])
            redirect(action:show, id: result.inventoryItemInstance.id)
            return
        }

        //flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        render(view:'create', model:[inventoryItemInstance: result.inventoryItemInstance])
    }

    /**
    * Handles the use inventory item form submit in the show view.
    */
    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
    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.show(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")
            }

        }
    }

}
