module PBDebug
  def PBDebug.logonerr
    begin
      yield
    rescue
      PBDebug.log("**Exception: #{$!.message}\r\n#{$!.backtrace.inspect}")
      PBDebug.close # close log file before crashing (also transfers any leftover logs from buffer to file)
      pbPrintException($!)
    end
  end

  @@foldername = RTP.getSaveFolder + "Battle Logs/"
  @@filename = ""
  @@logfile = nil
  @@maxlogs = 5

  def PBDebug.filename
    return @@filename
  end

  def PBDebug.flush
    return if !$INTERNAL
    return if @@logfile.nil?
    @@logfile.flush
  end

  def PBDebug.log(msg)
    return if !$INTERNAL
    return if @@logfile.nil?
    @@logfile.write(msg + "\r\n") rescue nil
  end

  def PBDebug.open(name)
    @@logfile.close unless @@logfile.nil?
    if !$INTERNAL || name == ""
      PBDebug.disableLog
      return
    end
    Dir.mkdir(@@foldername) unless File.exist?(@@foldername)
    @@filename = @@foldername + "#{name}.txt"
    i = 1
    Dir.glob("#{@@foldername.gsub('\\', '/')}*.txt").grep(/\/\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2} - /).sort { |a, b|
      File.mtime(b) <=> File.mtime(a)
    }.each do |file|
      i += 1
      next unless i > @@maxlogs
      # The file may still be open by another instance of the game.
      begin
        File.delete(file)
      rescue Errno::EACCES => e
        puts "Permission denied: #{e.message}"
      end
    end
    @@logfile = File.open(@@filename, "a+b")
  end

  def PBDebug.close
    return if @@logfile.nil?
    PBDebug.flush
    @@logfile.close
    @@logfile = nil
  end

  def PBDebug.disableLog
    @@filename = ""
    @@logfile = nil
  end
end
