require File.expand_path('../../spec_helper', __FILE__)

describe AttachmentsController, :logged => :admin do

  let!(:project) { FactoryGirl.create(:project) }
  let!(:member) { FactoryGirl.create(:member, :project => project, user: User.current) }
  let!(:doc) { FactoryGirl.create(:document, :project => project) }
  let(:attachment) { FactoryGirl.create(:attachment, :file => fixture_file_upload('files/testfile.txt', 'text/plain')) }

  it 'increments downloads' do
    expect( attachment.downloads ).to eq 0
    get :download, :id => attachment.id
    expect( response ).to be_success
    expect( attachment.reload.downloads ).to eq 1
  end

  it 'increments downloads version' do
    attachment.update_attributes(:description => 'Update attachment to next version!')
    get :download, :id => attachment.versions.last.id, :version => true
    expect( response ).to be_success
    expect( attachment.reload.downloads ).to eq 1
  end

  it 'donwload attachments or version not create new revision' do
    get :download, :id => attachment.id
    expect( response ).to be_success
    expect( attachment.reload.versions.count ).to eq 1

    attachment.update_attributes(:description => 'Update attachment to next version!')

    3.times do |x|
      get :download, :id => attachment.versions.last.id, :version => true
      expect( response ).to be_success
      expect( attachment.reload.versions.count ).to eq 2
    end

  end

  it 'sends notifications when attachments are added to document' do
    ActionMailer::Base.deliveries = []

    with_user_pref('no_self_notified' => '0') do
      with_settings :notified_events => ['file_added'] do
        post :attach, {:attachments => [{:file => fixture_file_upload('files/testfile.txt', 'text/plain')}], :entity_type => 'Document', :entity_id => doc.id}
        expect(ActionMailer::Base.deliveries.size).to eq(1)
      end
    end
  end

  context 'REST API' do
    let(:attachment) { FactoryGirl.create(:attachment, :container => nil, :file => fixture_file_upload('files/testfile.txt', 'text/plain')) }
    let(:issue) { FactoryGirl.create(:issue, project: project) }

    it 'attach file' do
      expect {
        post :attach, {attach: {entity_type: 'Issue', entity_id: issue.id, attachments: [{token: attachment.token}]}, format: 'json', key: User.current.api_key}
      }.to change(issue.reload.attachments, :count).by 1
    end

    it 'wtf in api' do
      post :attach, {attach: {entity_type: 'Wtf', entity_id: 666, attachments: [{token: attachment.token}]}, format: 'json', key: User.current.api_key}
      expect(response.status).not_to eq(500)
    end

  end


end
