module Settings
  require "inifile"

  SETTINGS_FILE_NAME = Oneshot_UTF::SAVE_PATH + "/settings.ini"
  VAR_PROXIES = {
    # Audio
    bgm_volume: ->(val = nil) {
      Audio.bgm_volume = val unless val.nil?
      return Audio.bgm_volume
    },
    sfx_volume: ->(val = nil) {
      Audio.sfx_volume = val unless val.nil?
      return Audio.sfx_volume
    },
    audio_filters: ->(val = nil) {
      $game_temp.audio_filters = val unless val.nil?
      return $game_temp.audio_filters
    },

    # Graphics
    fullscreen: ->(val = nil) {
      Graphics.fullscreen = val unless val.nil?
      return Graphics.fullscreen
    },
    smoothing: ->(val = nil) {
      Graphics.smooth = val unless val.nil?
      return Graphics.smooth
    },
    frameskip: ->(val = nil) {
      Graphics.frameskip = val unless val.nil?
      return Graphics.frameskip
    },
    colorblind_mode: ->(val = nil) {
      $game_switches[252] = val unless val.nil?
      return $game_switches[252]
    },
    modglow: ->(val = nil) {
      $game_switches[427] = val unless val.nil?
      return $game_switches[427]
    },

    # Gameplay
    default_run: ->(val = nil) {
      $game_switches[251] = val unless val.nil?
      return $game_switches[251]
    },
    automash: ->(val = nil) {
      $game_switches[253] = val unless val.nil?
      return $game_switches[253]
    },

    # Misc
    edebug: ->(val = nil) {
      $game_switches[413] = val unless val.nil?
      return $game_switches[413]
    },

  }

  # Settings which shouldn't be saved/loaded from .ini
  # Stuff like crash reporting which are handled independantly of the settings file
  IGNORE_SERIALIZATION = []

  def self.load
    return unless File.exist?(SETTINGS_FILE_NAME)

    begin
      IniFile.load(SETTINGS_FILE_NAME)["global"].each do |k, v|
        s = k.to_sym
        VAR_PROXIES[s].call(v) if VAR_PROXIES[s] && !IGNORE_SERIALIZATION.include?(s)
      end
    rescue
      print "Failed parsing settings. Resetting..."
      File.delete(SETTINGS_FILE_NAME)
    end
  end

  def self.save
    settings = {}
    VAR_PROXIES.each do |k, v|
      settings[k] = v.call() unless IGNORE_SERIALIZATION.include?(k)
    end

    options = {
      filename: SETTINGS_FILE_NAME,
      content: {
        global: settings,
      },
    }
    IniFile.new(options).write()
  end
end
