class AssetSubItemService {

    boolean transactional = false

    def delete(params) {
        def result = [:]
        def fail = { Map m ->
            result.error = [ code: m.code, args: ["AssetSubItem", params.id] ]
            return result
        }

        result.assetSubItemInstance = AssetSubItem.get(params.id)

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

        if(result.assetSubItemInstance.assets)
            return fail(code:"assetSubItem.assets.associated")

        if(result.assetSubItemInstance.maintenanceActions)
            return fail(code:"assetSubItem.maintenanceActions.associated")

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

    }

    def create(params) {
        def result = [:]
        def fail = { Map m ->
            result.error = [ code: m.code, args: ["AssetSubItem", params.id] ]
            return result
        }

        result.assetSubItemInstance = new AssetSubItem()
        result.assetSubItemInstance.properties = params

        // pass in an asset to link to if provided.
        if(params.asset?.id)
            result.assetInstance = Asset.get(params.asset.id)

        // success
        return result
    }

    def save(params) {
        AssetSubItem.withTransaction { status ->
            def result = [:]

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

            result.assetSubItemInstance = new AssetSubItem(params)

            if(params.asset?.id) {
                result.assetInstance = Asset.get(params.asset.id)

                if(!result.assetInstance)
                    return fail(code:"assetSubItem.asset.not.found")
            }

            if(result.assetSubItemInstance.hasErrors() || !result.assetSubItemInstance.save(flush: true))
                return fail(code:"default.create.failure")

            if(result.assetInstance)
                result.assetInstance.addToAssetSubItems(result.assetSubItemInstance)

            // Success.
            return result

        } //end withTransaction
    } // save()

} // end class