#==============================================================================
# ** Main
#------------------------------------------------------------------------------
#  After defining each class, actual processing begins here.
#==============================================================================

$version = "v0.1-ALPHA3"

MKXP.allow_force_quit

at_exit do
  Wallpaper.reset
  save unless $game_switches[99] || ($game_system.map_interpreter.running? || !$scene.is_a?(Scene_Map))
end

def self.process_error(error)
  title = "#{error.class} : #{error.to_s}"
  description = ""

  error.backtrace.each do |line|
    description += "- #{line}\n"
  end
  description.chomp!("\n")

  # Anonymize data
  description = description.gsub(Dir.pwd, ".")
  description = description.gsub(Oneshot_UTF::GAME_PATH, "[GAME_PATH]")
  description = description.gsub(Oneshot_UTF::DOCS_PATH, "[DOCS_PATH]")
  description = description.gsub(Oneshot_UTF::SAVE_PATH, "[SAVE_PATH]")
  description = description.gsub(Oneshot_UTF::USER_NAME, "[USER_NAME]")
  description = description.gsub(Game_Oneshot.get_user_name.force_encoding("utf-8"), "PLAYER")

  return title, description
end

begin
  $console = Graphics.fullscreen
  Graphics.frame_rate = 60
  Font.default_size = 20

  # Load persistent data
  Persistent.load

  # Prepare for transition
  Graphics.freeze
  $demo = false
  $GDC = false
  # Make scene object (title screen)
  $scene = Scene_Title.new
  Oneshot.allow_exit false
  # Call main method as long as $scene is effective
  while $scene != nil
    $scene.main
  end
  # Fade out
  Graphics.transition(20)
  Oneshot.allow_exit true
rescue Errno::ENOENT
  filename = $!.message.sub("No such file or directory - ", "")
  print("Unable to find file #{filename}.")
rescue Exception => e
  title, description = process_error(e)
  print "An error has occurred!\nPlease report this on the Discord server.\nLink to the Discord server can be found on the mods page.\n\n#{title}\n#{description}"
  puts title
  puts description
  Oneshot.exiting true
  Graphics.transition(20)
  Journal.set "" if Journal.active?
  Oneshot.allow_exit true
end
