require 'spec_helper'
require 'fileutils'

# these tests avoid the use of ActiveRecord and FactoryGirl to do blackbox, non test-instrumented tests
describe UnusedMusicNotationCleaner do
  include UsesTempFiles

  UNUSED_NOTATION_TEMP_FILE='detail.png'

  in_directory_with_file(UNUSED_NOTATION_TEMP_FILE)

  before do
    content_for_file("this is music notation test file")
  end

  let(:check) { UnusedMusicNotationCleaner.new }

  describe "integration" do

    before(:all) do
      MusicNotation.delete_all
    end

    it "be OK with no music notations" do
      MusicNotation.count().should == 0
      check.should_not_receive(:handle_notifications)
      check.run
    end


    it "find no music notataions if music_session_id is nil and created at 1 hour ago" do
      notation = MusicNotation.new

      notation.file_url = File.open(UNUSED_NOTATION_TEMP_FILE)
      notation.size = 10
      notation.user = FactoryGirl.create(:user)
      notation.created_at = Time.now - 1.hours
      notation.save!

      check.should_not_receive(:handle_notifications)
      check.run
    end

    it "find no music notataion if music_session_id is not nil and session_removed_at is in 1 hour" do
      music_session = FactoryGirl.create(:music_session, :session_removed_at => Time.now - 1.hours)

      notation = MusicNotation.new
      notation.file_url = File.open(UNUSED_NOTATION_TEMP_FILE)
      notation.size = 10
      notation.user = FactoryGirl.create(:user)
      notation.created_at = Time.now - 1.hours
      notation.music_session = music_session
      notation.save!

      check.run
    end

    it "find music notataions if music_session_id is nil and created at 2 days ago" do
      notation = MusicNotation.new
      notation.file_url = File.open(UNUSED_NOTATION_TEMP_FILE)
      notation.size = 10
      notation.user = FactoryGirl.create(:user)
      notation.created_at = Time.now - 2.days
      notation.save!

      check.should_receive(:handle_notifications)
      check.run
    end

    it "find music notataion if music_session_id is not nil and session_removed_at 2 days ago" do
      music_session = FactoryGirl.create(:music_session, :session_removed_at => Time.now - 2.days)

      notation = MusicNotation.new
      notation.file_url = File.open(UNUSED_NOTATION_TEMP_FILE)
      notation.size = 10
      notation.user = FactoryGirl.create(:user)
      notation.created_at = Time.now - 3.days
      notation.music_session = music_session
      notation.save!

      check.should_receive(:handle_notifications)
      check.run
    end
  end
end
