require "spec_helper"

describe SocialAvatarProxy::Avatar do
  subject do
    SocialAvatarProxy::Avatar.new(id)
  end

  let(:id) { "http://www.example.com/" }
  
  let(:response) { nil }
  
  let(:successful_response) do
    response = Net::HTTPSuccess.new("1.1", 200, "Success")
    response.stub(:stream_check).and_return(true)
    response.stub(:read_body).and_return("data")
    response
  end
  
  before(:each) do
    klass = SocialAvatarProxy::RemoteFileResolver
    klass.any_instance.stub(:resolve).and_return(response)
  end
  
  describe "#remote_url" do
    it "should return the identifier" do
      expect(subject.remote_url).to eq(id)
    end
  end
  
  context "with a valid response" do
    let(:response) { successful_response }
    
    describe "#exist?" do
      it "should be true" do
        expect(subject.exist?).to be_true
      end
    end
    
    describe "#body" do
      it "should be able to download the body" do
        expect(subject.body).to eq "data"
      end
    end
    
    describe "#content_type" do
      context "with a content-type header" do
        before(:each) do
          response.stub(:[]).with("content-type").and_return("image/png")
        end
        
        it "should return the header value" do
          expect(subject.content_type).to eq("image/png")
        end
      end
      
      context "with a content-type header" do
        it "should return image/jpeg as the default" do
          expect(subject.content_type).to eq("image/jpeg")
        end
      end
    end
    
    context "with a last-modified header" do
      before(:each) do
        response.stub(:[]).with("last-modified").and_return(timestamp.httpdate)
      end
      
      let(:timestamp) { Time.now - 86400 }
      
      describe "#last_modified" do
        it "should parse the header and return a DateTime object" do
          expect(subject.last_modified.to_i).to eq(timestamp.to_i)
        end
      end
    end
    
    context "with no last-modified header" do
      describe "#last_modified" do
        it "should return the current time" do
          expect(subject.last_modified.to_i).to eq(Time.now.to_i)
        end
      end
    end
  end
end