# coding: utf-8
require_relative "spec_helper"
include ImageDownloader

describe Finder do
  let(:finder) { Finder.new('http://google.com') } 
  let(:google_uri) { URI('http://google.com') }
  subject { finder }
  before { finder.stub(:open) }

  it { should be_an_instance_of(Finder) }

  it { should respond_to :uri }
  it { should_not respond_to :uri= }
  its(:uri) { should eq google_uri }

  it { should respond_to :document }
  it { should_not respond_to :document= }
  its(:document) { should be_an_instance_of(Nokogiri::HTML::Document) }

  it { should respond_to :images }
  it { should_not respond_to :images= }

  its(:images) { should be_a_kind_of(Array) }

  it { should respond_to :[] }
  it { should be_a_kind_of(Enumerable) }

  it "should provide lazy-loading" do 
    expect(finder.document_loaded?).to be_false
    finder.document
    expect(finder.document_loaded?).to be_true
  end  

  context "when initialized with invalid url" do
    it "should raise an error" do
      invalid_urls = %w(without_protocol.com http://without_domain just_string) << "http://with space.com"
      invalid_urls.each do |url|
        expect { Finder.new(url) }.to raise_error 
      end
    end
  end 

  context "when HTML doesn't contain any images" do
    before { finder.stub(:open).and_return("") }

    context "#images" do
      subject { finder.images }

      its(:size) { should eq(0) }
    end
  end

  context "when HTML contains images" do
    let(:finder) { Finder.new('http://google.com/one/two/three') }
    let(:html) do
      %w[
        http://google.com/three/image.png
        image.png
        ../image.png
        ../../image.png
        /image.png
      ].map { |href| "<img src=\"#{href}\" />" }.join(' ')
    end
    before { finder.stub(:open).and_return(html) }

    context "#images" do
      subject { finder.images }

      its(:size) { should_not be_zero }
    end

    it "should create absolute url for any kind of valid image 'src' attribute" do
      expected_images = %w[
        http://google.com/three/image.png
        http://google.com/one/two/image.png
        http://google.com/one/image.png
        http://google.com/image.png
        http://google.com/image.png
      ]

      ary = finder.each_with_object([]) { |href, ary| ary << href }
      expect(ary).to eq expected_images
    end
  end
end