module ViewModels
  class RecipeCriteria

    SORT_COLUMNS = :created_at, :name, :rating, :total_time
    PARAMS = [:sort_column, :sort_direction, :page, :per, :name, :tags]

    attr_accessor *PARAMS

    def initialize(params = nil)
      params ||= {}
      PARAMS.each do |attr|
        setter = "#{attr}="
        if params[attr].present?
          self.send(setter, params[attr])
        end
      end
    end

    def sort_column
      default(@sort_column.to_s.to_sym, SORT_COLUMNS.first, ->(v) {SORT_COLUMNS.include?(v)} )
    end

    def sort_direction
      default(@sort_direction.to_s.to_sym, :desc, ->(v) {[:asc, :desc].include?(v)} )
    end

    def page
      default(@page, 1, ->(v) { v.to_i > 0 })
    end

    def per
      default(@per, 50, ->(v) { v.to_i > 0 })
    end

    protected

    def default(val, default_val, valid_proc)
      if val.blank? || !valid_proc.call(val)
        default_val
      else
        val
      end
    end

  end
end