DEFAULT_PREFS = YAML.load_file("#{Rails.root}/config/default_preferences.yml")

class UserPreferences
  def self.dump(value)
    process(value).to_yaml
  end

  def self.load(string)
    stored_prefs = YAML.load(string || "{}")
    DEFAULT_PREFS.merge(stored_prefs).with_indifferent_access
  end

  def self.is_integer?(value)
    value.to_i.to_s == value
  end

  def self.process(hash)
    hash.each do |key, value|
      if value == "true"
        hash[key] = true
      elsif value == "false"
        hash[key] = false
      elsif value.is_a?(String) && is_integer?(value)
        hash[key] = value.to_i
      end
    end
    hash.stringify_keys!.to_h
  end
end
