require 'singleton'

# class representing a file logger
class LogManager
  include Singleton

  INFO = "INFO"
  ERROR = "ERROR"
  WARN = "WARNING"

  def initialize()
    now = Time.now.strftime("%d-%m-%Y")
    @filename = "#{now.to_s}.log"
  end

  def setFilename(tool_dir, prefix)
    log_dir = "#{tool_dir}/"
    if not File.directory?(log_dir)
      Dir.mkdir log_dir
    end
    @path = "#{log_dir}#{prefix}_#{@filename}"
    File.open(@path, 'a') { |file| file.puts "------------------------------------------------" + "\r\n" }
  end

  def getLogPath()
    return @path
  end

  def info(message, print=FALSE)
    log(message, print, type=INFO)
  end

  def warn(message, print=FALSE)
    log(message, print, type=WARN)
  end

  def error(message, print=FALSE)
    log(message, print, type=ERROR)
  end

  def abortExecution(error=TRUE)
    info("PROCESS ABORTED")
    if error
      puts
      unless @path.nil?
        puts "PROCESS ABORTED : For more detailed information, please refer to the log file '#{@path}'"
      end
    end
    exec("Process.kill 9, Process.pid >/dev/null 2>&1")
  end

  def logOutOfMemoryError(reference)
    error("The data chunk size is too large. Proccess aborted for #{reference}.", print=TRUE)
    info("Please, check the help or README.md to customize the chunk size.", print=TRUE)
  end

  def logArray(messagesArray, print, type)
    messagesArray.each { |message| log(message, print, type) }
  end

  def log(message, print=FALSE, type=INFO)
    if message.kind_of?(Array)
      logArray(message, print, type)
      return
    end
    if print
      puts "[#{type}] #{message}"
    end
    now = Time.now.strftime("%d-%m-%Y %H:%M:%S").to_s
    entry = "#{now}  -  #{type} : #{message}" + "\r\n"
    unless @path.nil?
      File.open(@path, 'a') { |file| file.puts entry }
    end
  end

end
