SRC_DIR = '../../src/log/'

utils = require '../TestUtils.coffee'
Addr64 = (require SRC_DIR + 'Addr64.coffee').Addr64
Log = (require SRC_DIR + 'Log.coffee').Log
LoggableIterator = (require SRC_DIR + 'LoggableIterator.coffee').LoggableIterator
RandomAccessLoggableIterator =
  (require SRC_DIR + 'RandomAccessLoggableIterator.coffee').
  RandomAccessLoggableIterator
LoggableToWrite = (require SRC_DIR + 'LoggableToWrite.coffee').LoggableToWrite
LogConfig = (require SRC_DIR + 'LogConfig.coffee').LogConfig
ArrayByteIterable =
  (require SRC_DIR + '../database/impl/iterate/ArrayByteIterable.coffee').
  ArrayByteIterable

N = 300
Nstep = 100
NPages = 10
log = new Object()

exports.setUp = (callback) =>
  path = utils.getNewDirName()
  config = LogConfig.create()
  config.setDir path
  config.setFileSize 1
  config.setCachePageSize 256
  config.setCacheOpenFilesCount NPages
  log = Log.create$LogConfig config

  writeToLog = () =>
    writeFromJtoK = (j, k) =>
      log.once 'flush', () =>
        writeFromJtoK j + Nstep, k + Nstep
      if k <= N
        for i in [j..k]
          b = ArrayByteIterable.create$Buffer new Buffer("Hello " + i.toString())
          d = LoggableToWrite.create$int$ByteIterable$int 2, b, 2
          log.write$Loggable d
        log.flush$emit()
      else
        log.close$emit()
    writeFromJtoK 1, Nstep

  writeToLog()
  callback()

exports.testLoggableIterator = (test) ->
  n1 = 0
  li = LoggableIterator.create$Log$Addr64 log, (Addr64.create$int$int 0, 0)
  li.on 'next', (result) ->
    test.ok (result.getType() == 2) || (result.getType() == 0)
    if result.getType() != 0
      test.equal result.getStructureId(), 2
      n1 += 1
      if n1 in [1..9]
        test.equal result.getDataLength(), 7
      else if n1 in [10..99]
        test.equal result.getDataLength(), 8
      else if n1 in [100..999]
        test.equal result.getDataLength(), 9
      else
        test.equal result.getDataLength(), 10
    if li.hasNext()
      res = li.next$emit()
    else
      test.done()
  res = li.next$emit()

exports.testRandomAccessLoggableIterator = (test) ->
  n2 = 0
  li = RandomAccessLoggableIterator.create$Log$Addr64 log,
          (Addr64.create$int$int 0, 0)
  li.on 'next', (result) ->
    test.ok (result.getType() == 2) || (result.getType() == 0)
    if result.getType() != 0
      test.equal result.getStructureId(), 2
      n2 += 1
      if n2 in [1..9]
        test.equal result.getDataLength(), 7
      else if n2 in [10..99]
        test.equal result.getDataLength(), 8
      else if n2 in [100..999]
        test.equal result.getDataLength(), 9
      else
        test.equal result.getDataLength(), 10
    if li.hasNext()
      res = li.next$emit()
    else
      test.done()
  res = li.next$emit()
