
package dbmodel

  /** Version 11.1
   *
   *  Miscellaneous modules for error messages and resource tracking.
   *
   *  Wong Limsoon
   *  12 May 2023
   */



   /** An object to store a flag to indicate whether we are in
    *  "debugging mode", and a function for printing diagnostic
    *  messages when we are in debugging mode.
    */

  object DEBUG:

      var debug = false

      def message(msg: Any) = if debug then System.err.println(msg)

  end DEBUG



  /** [[Resource]] trait is inherited by other objects that
   *  have resources (e.g. open files) associated with them.
   *  This trait provides methods for simple management of
   *  the associated resources (e.g. closing files or garbage
   *  collecting closed temporary files.
   */

  object RESOURCE:

    import java.lang.AutoCloseable

    trait Resource extends AutoCloseable:

      var held: Seq[AutoCloseable] = Seq()  // Resources held

      def use(resources: AutoCloseable*): this.type =
        held = resources ++ held 
        this

      def userev(resources: AutoCloseable*): this.type = 
        held = held ++ resources
        this
    
      def close(): Unit = 
        held.foreach { r => 
          if r != null then r.close() 
          else DEBUG.message("*** Resource.close: null resource ***")
        }
        held = Seq()


    object Resource:

      /** Constructors for making a [[AutoCloseable]] object into a
       *  managed resource associated with the inheriting object.
       */

      def apply(resource: AutoCloseable): Resource =
        new Resource { held = Seq(resource) }

      def closeable(cl: () => Unit): AutoCloseable = 
        new java.lang.AutoCloseable { def close(): Unit = cl() } 


      /** Function to close given resources
       */

      def closeAll(resources: AutoCloseable*): Unit = 
        resources.foreach(_.close())
  

      /** Run a piece of codes and attach resources to the result
       */

      def doWith[R<:Resource](r: AutoCloseable*)(f: => R): R = f.userev(r: _*)

    end Resource



