import org.apache.commons.collections.list.LazyList
import org.apache.commons.collections.FactoryUtils

class TaskProcedure {

    Task linkedTask

    def getDescription() { linkedTask.description }
    def getAsset() { linkedTask.primaryAsset }

    List maintenanceActions = new ArrayList()
    List documentReferences = new ArrayList()
    List revisions = new ArrayList()

    static hasMany = [maintenanceActions: MaintenanceAction,
                                    documentReferences: DocumentReference,
                                    revisions: TaskProcedureRevision]

    def getMaintenanceActionLazyList() {
        return LazyList.decorate(maintenanceActions, FactoryUtils.instantiateFactory(MaintenanceAction.class))
    }

    def getDocumentReferenceLazyList() {
        return LazyList.decorate(documentReferences, FactoryUtils.instantiateFactory(DocumentReference.class))
    }

    // The current revision number is equal to the count of the revisions created.
    // More efficient than loading the entire revisions list and using size().
    // WithTransaction is used to allow calling in a transaction however objects
    // in the current transaction must not trigger DataIntegrityViolationException.
    def getRevision() {
        def revision
        TaskProcedure.withTransaction {
            revision = TaskProcedureRevision.countByTaskProcedure(this)
        }
        return revision
    }

    // Get a specific revision.
    def getRevision(revision) {
        def taskProcedureRevision
        TaskProcedure.withTransaction {
            taskProcedureRevision = TaskProcedureRevision.findByTaskProcedureAndRevision(this, revision)
        }
        return taskProcedureRevision
    }

    // Get the latest revision of this procedure.
    def getLatestRevision() {
        def taskProcedureRevision
        TaskProcedure.withTransaction {
            taskProcedureRevision = TaskProcedureRevision.findByTaskProcedureAndRevision(this, this.revision)
        }
        return taskProcedureRevision
    }

    static mapping = {
        linkedTask lazy:false
        revisions batchSize: 10
        maintenanceActions cascade:"all-delete-orphan"
        documentReferences cascade:"all-delete-orphan"
        revisions cascade:"all-delete-orphan"
    }

//     static belongsTo = []

    static constraints = {
    }

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