package ocelot.desktop.audio

import ocelot.desktop.util.Logging
import org.lwjgl.openal.AL10

import java.nio.ByteBuffer
import scala.util.control.Exception.catching

case class SoundSamples(private var data: ByteBuffer, rate: Int, format: SoundSamples.Format.Value) extends Logging {
  if (!data.isDirect) {
    data = ByteBuffer.allocateDirect(data.remaining()).put(data)
    data.flip()
  }

  def genBuffer(): Option[Int] = Audio.synchronized {
    if (Audio.isDisabled) return None

    catching(classOf[OpenAlException]) opt {
      val bufferId = AL10W.alGenBuffers()
      val formatId = format match {
        case SoundSamples.Format.Stereo16 => AL10.AL_FORMAT_STEREO16
        case SoundSamples.Format.Mono16 => AL10.AL_FORMAT_MONO16
        case SoundSamples.Format.Mono8 => AL10.AL_FORMAT_MONO8
      }

      AL10W.alBufferData(bufferId, formatId, data, rate)

      bufferId
    }
  }
}

object SoundSamples {
  object Format extends Enumeration {
    val Stereo16, Mono8, Mono16 = Value
  }
}
