package ocelot.desktop.util

import ocelot.desktop.Settings

import java.io.{File, FileOutputStream, IOException, RandomAccessFile}
import java.nio.ByteBuffer
import java.nio.channels.Channels
import scala.util.{Try, Using}

object FileUtils extends Logging {
  def load(filename: String): ByteBuffer = {
    val file = new RandomAccessFile(filename, "r")
    val inChannel = file.getChannel

    try {
      val fileSize = inChannel.size
      val buffer: ByteBuffer = ByteBuffer.allocate(fileSize.toInt)
      inChannel.read(buffer)
      buffer.flip
      buffer
    } catch {
      case e: IOException =>
        logger.error(s"Cannot load file: $filename", e)
        null
    } finally {
      if (file != null) file.close()
      if (inChannel != null) inChannel.close()
    }
  }

  def unpackResource(resource: String, target: File): Try[File] = Try {
    val configResource = classOf[Settings].getResource(resource)
    Using.resources(Channels.newChannel(configResource.openStream()), new FileOutputStream(target).getChannel) {
      (in, out) =>
        out.transferFrom(in, 0, Long.MaxValue)
        target.setReadable(true, false)
        target.setWritable(true, false)
        target.setExecutable(false, false)
        target
    }
  }
}
