class Dunlop::UserSettings
  attr_reader :record, :storage
  def initialize(record, storage)
    @record, @storage = record, storage
  end

  def get(*path_spec)
    current_settings_level = storage
    Array.wrap(path_spec).each do |level|
      current_settings_level = current_settings_level[level.to_s]
      return nil unless current_settings_level
    end
    current_settings_level
  end

  def set(*args)
    value = args.pop
    if value.is_a?(Hash) and args.empty? # settings.set(a: 4) assignment
      value.each do |k, v|
        set(k, v)
      end
    else
      value = value.deep_stringify_keys if value.respond_to?(:deep_stringify_keys)
      args = args.first if args.first.is_a?(Array)
      current_settings_level = storage
      Array.wrap(args)[0..-2].each do |level|
        current_settings_level[level.to_s] ||= {}
        current_settings_level = current_settings_level[level.to_s]
      end
      current_settings_level[args.last.to_s] = value
      record.settings_storage = storage
    end
    value
  end

  def set!(*args)
    set(*args)
    record.save
  end
end
