fs = (require 'fs')

# All the methods are syncronous, as they are rearly used.
# TODO Maybe it's better to write async versions.
class IOUtil
  # Remove directory with file in it.
  #
  # @param directory
  @removeDirectory$String: (directory) ->
    if directory[directory.length - 1] != '/' then directory += '/'
    files = fs.readdirSync directory
    if files.length != 0
      for i in [0..files.length - 1]
        stats = fs.statSync directory + files[i]
        if stats.isFile()
          fs.unlinkSync directory + files[i]
        else if stats.isDirectory()
          IOUtil.removeDirectory$String directory + files[i]
    fs.rmdirSync directory
    return undefined

  # Make directory with all parents if necessary.
  #
  # @param directory
  @makeDirectory$String: (directory) ->
    if directory[directory.length - 1] != '/' then directory += '/'
    i = 1
    l = directory.length - 1
    while i < l
      i += 1
      while directory[i] != '/'
        i += 1
      dir = directory.slice 0, i
      try
        fs.mkdirSync dir
      catch e
    return undefined

  # Get the overall size of the directory (in bytes).
  #
  # @param directory
  # @return size in bytes.
  @getDirectorySize$String: (directory) ->
    size = 0
    if directory[directory.length - 1] != '/' then directory += '/'
    files = fs.readdirSync directory
    if files.length != 0
      for i in [0..files.length - 1]
        stats = fs.statSync directory + files[i]
        if stats.isFile()
          size += stats.size
        else if stats.isDirectory()
          size += IOUtil.getDirectorySize$String directory + files[i]
    return size

exports.IOUtil = IOUtil