import org.codehaus.groovy.grails.commons.ConfigurationHolder

class Asset {

    Section section

    String name
    String description = ""
    String comment = ""
    boolean isActive = true
    boolean hasRegulatoryRequirements = false

    static hasMany = [assetSubItems: AssetSubItem,
                                    maintenanceActions: MaintenanceAction,
                                    assetExtendedAttributes: AssetExtendedAttribute]

    static belongsTo = [Section]

    static constraints = {
        name(maxSize:50, unique:true, blank:false)
        description(maxSize:75)
        comment(maxSize:500)
        isActive()
        section()
    }

    static mapping = {
        assetSubItems(batchSize:1000)
    }

    String toString() {
        "${this.name}"
    }

    static searchable = {
        root false // only index as a component of InventoryItem.
        only = ['name', 'description', 'comment']
    }

    def afterUpdate = {
        // Update the Inventory searchable index, since cascading in searchable-0.5.5 is broken.
        if(ConfigurationHolder.config.appSearchable.cascadeOnUpdate) {
            try {
                InventoryIndexJob.triggerNow(['calledBy':'Asset afterUpdate{}'])
            }
            catch(e) {log.error e}
        } // if
    } // afterUpdate

    //  This additional setter is used to convert the checkBoxList string or string array
    //  of ids selected to the corresponding domain objects.
    public void setAssetSubItemsFromCheckBoxList(ids) {
        def idList = []
        if(ids instanceof String) {
                if(ids.isInteger())
                    idList << ids.toInteger()
        }
        else {
            ids.each() {
                if(it.isInteger())
                    idList << it.toInteger()
            }
        }
        this.assetSubItems = idList.collect { AssetSubItem.get( it ) }
    }

}

