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

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

    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(controller: "assetDetailed", params:params) }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_AssetManager', 'ROLE_AssetUser'])
    def show = {
        def assetSubItemInstance = AssetSubItem.get( params.id )

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

    def delete = {
        def assetSubItemInstance = AssetSubItem.get( params.id )
        if(assetSubItemInstance) {
            try {
                assetSubItemInstance.delete(flush:true)
                flash.message = "AssetSubItem ${params.id} deleted"
                redirect(controller: "assetDetailed", action: "search")
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.errorMessage = "AssetSubItem ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "AssetSubItem not found with id ${params.id}"
            redirect(controller: "assetDetailed", action: "search")
        }
    }

    def edit = {
        def assetSubItemInstance = AssetSubItem.get( params.id )

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

    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", "assetSubItem.optimistic.locking.failure", "Another user has updated this AssetSubItem while you were editing.")
                    render(view:'edit',model:[assetSubItemInstance:assetSubItemInstance])
                    return
                }
            }

            assetSubItemInstance.properties = params

//             if(!assetSubItemInstance.asset && !assetSubItemInstance.parentItem) {
//                 flash.message = "Either an asset or parentItem is required."
//                 render(view:'edit',model:[assetSubItemInstance:assetSubItemInstance])
//                 return
//             }
// 
//             if(assetSubItemInstance.asset && assetSubItemInstance.parentItem) {
//             flash.message = "Both an asset and parentItem may not be specified at the same time."
//                 render(view:'edit',model:[parentItem:parentItem])
//                 return
//             }

            if(!assetSubItemInstance.hasErrors() && assetSubItemInstance.save(flush: true)) {
                flash.message = "AssetSubItem ${params.id} updated"

                if(assetSubItemInstance.assets)
                    redirect(controller: "assetDetailed", action:"show", id: assetSubItemInstance.assets.toArray()[0].id)
                else {
                    //Get the top parentItem.
                    def parentItem = 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: assetSubItemInstance.id) // End stop if all else fails.
                }
            }
            else {
                render(view:'edit',model:[assetSubItemInstance:assetSubItemInstance])
            }
        }
        else {
            flash.message = "AssetSubItem not found with id ${params.id}"
            redirect(controller: "assetDetailed", action: "search")
        }
    }

    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: ["AssetSubItem", 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
