import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.apache.commons.lang.WordUtils

@Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_AssetManager'])
class AssetSubItemDetailedController extends BaseController {

    def filterService
    def exportService
    def assetSubItemService

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

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

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

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_AssetManager', 'ROLE_AssetUser'])
    def search = {

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

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

        def assetSubItemInstanceList = []
        def assetSubItemInstanceTotal
        def filterParams = [:]

        // Quick Search:
        if(!params.filter) {
            assetSubItemInstanceList = AssetSubItem.list( params )
            assetSubItemInstanceTotal = AssetSubItem.count()
            filterParams.quickSearch = params.quickSearch
        }
        else {
        // filterPane:
            assetSubItemInstanceList = filterService.filter( params, AssetSubItem )
            assetSubItemInstanceTotal = filterService.count( params, AssetSubItem )
            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 = "AssetSubItem List."

            response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=assets.${params.extension}")
            List fields = ["name",
                                "description"]
            Map labels = ["name": "AssetSubItem",
                                "description": "Description"]

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

            exportService.export(params.format,
                                                response.outputStream,
                                                assetSubItemInstanceList.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[ assetSubItemInstanceList: assetSubItemInstanceList,
                assetSubItemInstanceTotal: assetSubItemInstanceTotal,
                filterParams: filterParams ]

    } // end search()

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_AssetManager', 'ROLE_AssetUser'])
    def show = {

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

        def assetSubItemInstance = AssetSubItem.get( params.id )

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

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

        if(!result.error) {
            flash.message = g.message(code: "default.delete.success", args: ["AssetSubItem", 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 assetSubItemInstance = AssetSubItem.get( params.id )

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

        def possibleParentItems = assetSubItemService.possibleParentItems(assetSubItemInstance)

        return [ assetSubItemInstance : assetSubItemInstance, possibleParentItems: possibleParentItems ]
    }

    def update = {
        def assetSubItemInstance = AssetSubItem.get( params.id )
        if(assetSubItemInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(assetSubItemInstance.version > version) {

                    assetSubItemInstance.errors.rejectValue("version", "default.optimistic.locking.failure")
                    render(view:'edit',model:[assetSubItemInstance:assetSubItemInstance])
                    return
                }
            }

            assetSubItemInstance.properties = params

            use(WordUtils) {
                assetSubItemInstance.name = assetSubItemInstance.name.capitalize()
                assetSubItemInstance.description = assetSubItemInstance.description.capitalize()
            }

            if(assetSubItemInstance.assets) {
                assetSubItemInstance.parentItem = null
            }

            if(!assetSubItemInstance.hasErrors() && assetSubItemInstance.save(flush: true)) {
                flash.message = "Sub Item '${assetSubItemInstance.name}' updated"
                redirect(action:"show", id: assetSubItemInstance.id)
            }
            else {
                render(view:'edit',model:[assetSubItemInstance:assetSubItemInstance])
            }
        }
        else {
            flash.message = "AssetSubItem not found with id ${params.id}"
            redirect(action: "search")
        }
    } // update

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

        if(!result.error)
            return [assetSubItemInstance: result.assetSubItemInstance, assetInstance: result.assetInstance]

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

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

        if(!result.error) {
            // Success.
            flash.message = g.message(code: "default.create.success", args: ["Sub Item", "'${result.assetSubItemInstance.name}'"])

            /// @todo: This just grabs the first parent in an unsorted list and needs improving.
            if(result.assetSubItemInstance.assets)
                redirect(controller: "assetDetailed", action:"show", id: result.assetSubItemInstance.assets.toArray()[0].id)
            else {
                //Get the top parentItem.
                def parentItem = result.assetSubItemInstance.parentItem
                def i = 0
                while(parentItem?.parentItem) {
                    parentItem = parentItem.parentItem
                    // Protect against infinite recurrsion.
                    i++
                    if(i > 100)
                        break
                }

                if(parentItem?.assets)
                    redirect(controller: "assetDetailed", action:"show", id: parentItem.assets.toArray()[0].id)
                else
                    redirect(action:"show", id: result.assetSubItemInstance.id) // End stop if all else fails.
            }
            return
        }

        if(result.error.code == "assetSubItem.asset.not.found")
            flash.errorMessage = g.message(code: "default.create.success")

        render(view:'create', model:[assetSubItemInstance: result.assetSubItemInstance, assetInstance: result.assetInstance])
    }

} // end class
