class Admin::SettingsController < Admin::BaseController
  before_action :set_current_section

  def index
  end

  def update_settings
    @errors = ActiveModel::Errors.new(Setting.new)
    changed_keys = []

    setting_params.keys.each do |key|
      next if setting_params[key].nil? ||
              (Setting.send(key).to_s == setting_params[key].strip)
      changed_keys.push(key)
      setting = Setting.new(var: key)
      setting.value = setting_params[key].strip
      unless setting.valid?
        @errors.merge!(setting.errors)
      end
    end

    if @errors.any?
      render :index and return
    end

    changed_keys.each do |key|
      Setting.send("#{key}=", setting_params[key].strip)
    end
  end

  private

    def set_current_section
      @current_section = :settings
    end

    def setting_params
      params.require(:setting).permit(Setting.editable_keys.map(&:to_sym))
    end
end
