class SectionService {

    boolean transactional = false

    def assetSubItemService
    def assetService

    def delete(params) {
        Section.withTransaction { status ->
            def result = [:]

            def fail = { Map m ->
                status.setRollbackOnly()
                if(result.sectionInstance && m.field)
                    result.sectionInstance.errors.rejectValue(m.field, m.code)
                result.error = [ code: m.code, args: ["Section", params.id] ]
                return result
            }

            result.sectionInstance = Section.get(params.id)

            if(!result.sectionInstance)
                return fail(code:"default.not.found")

            if(result.sectionInstance.maintenanceActions)
                return fail(code:"maintenanceActions.still.associated")

            // Delete assets which in turn delete orphan assetSubItems.
            def assets = new ArrayList(result.sectionInstance.assets) // avoid ConcurrentModificationException.
            def r
            for(asset in assets) {
                result.sectionInstance.removeFromAssets(asset)
                r = assetService.delete(id: asset.id)
                if(r.error) {
                    log.debug r.error
                    fail(code:"section.asset.delete.failure")
                    break
                }
            }

            if(result.error)
                return result

            try {
                result.sectionInstance.delete(flush:true)
                return result //Success.
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                return fail(code:"default.delete.failure")
            }

        } // end withTransaction
    } // end delete()

} // end class