#   Copyright (c) 2010-2011, Diaspora Inc.  This file is
#   licensed under the Affero General Public License version 3 or later.  See
#   the COPYRIGHT file.

require 'spec_helper'

describe ShareVisibility do
  describe '.batch_import' do
    before do
      @post = Factory(:status_message, :author => alice.person)
      @contact = bob.contact_for(alice.person)
    end

    it 'returns false if share is public' do
      @post.public = true
      @post.save
      ShareVisibility.batch_import([@contact.id], @post).should be_false
    end

    it 'creates a visibility for each user' do
      lambda {
        ShareVisibility.batch_import([@contact.id], @post)
      }.should change {
        ShareVisibility.exists?(:contact_id => @contact.id, :shareable_id => @post.id, :shareable_type => 'Post')
      }.from(false).to(true)
    end

    it 'does not raise if a visibility already exists' do
      ShareVisibility.create!(:contact_id => @contact.id, :shareable_id => @post.id, :shareable_type => 'Post')
      lambda {
        ShareVisibility.batch_import([@contact.id], @post)
      }.should_not raise_error
    end

    context "scopes" do
      describe '.for_a_users_contacts' do
        before do
          alice.post(:status_message, :text => "Hey", :to => alice.aspects.first)
        end

        it 'searches for share visibilies for all users contacts' do
          contact_ids = alice.contacts.map{|c| c.id}
          ShareVisibility.for_a_users_contacts(alice).should == ShareVisibility.where(:contact_id => contact_ids).all
        end
      end

      describe '.for_contacts_of_a_person' do
        it 'searches for share visibilties generated by a person' do

          contact_ids = alice.person.contacts.map{|c| c.id}
          
          ShareVisibility.for_contacts_of_a_person(alice.person) == ShareVisibility.where(:contact_id => contact_ids).all
            
        end
      end
    end
  end
end
