module PageHelpers
  module PageVerifier
    # Similar concept to PageObject::PagePopulator#populate_page_with
    def verify_page_has(data, options = {})
      options[:timeout] ||= 15 # default if the :timeout key is not specified in the method call
      data.each do |key, value|
        if options[:wait]
          send("#{key}_element").element.wait_until(options[:timeout], &:present?)
        else
          fail "element :#{key} is not present on page!" unless send("#{key}_element").element.present?
        end

        dom_value = get_dom_value(key)
        expect(dom_value).to eq(value), "expected element :#{key} to be: #{value}, got: #{dom_value}"
      end
    end

    private

    def get_dom_value(key)
      if checkbox?(key)
        checkbox_checked?(key)
      elsif radiobutton?(key)
        radio_selected?(key)
      elsif text_field?(key)
        text_value(key)
      end
    end

    def text_value(key)
      send key.to_s
    end

    def checkbox_checked?(key)
      send "#{key}_checked?"
    end

    def radio_selected?(key)
      send "#{key}_selected?"
    end

    def text_field?(key)
      respond_to?("#{key}=".to_sym)
    end

    def checkbox?(key)
      respond_to?("check_#{key}".to_sym)
    end

    def radiobutton?(key)
      respond_to?("select_#{key}".to_sym)
    end
  end
end
