require 'spec_helper'

describe JamTrackTrack do
  include CarrierWave::Test::Matchers
  include UsesTempFiles

  it "created" do
    jam_track_track = FactoryGirl.create(:jam_track_track)
    jam_track_track.jam_track.should_not be_nil
    jam_track_track.jam_track.reload
    jam_track_track.jam_track.jam_track_tracks.should == [jam_track_track]
  end

  describe "validations" do
    it "position" do
      jam_track = FactoryGirl.create(:jam_track)
      jam_track_track_1 = FactoryGirl.create(:jam_track_track, position: 1, jam_track: jam_track)
      jam_track_track_2 = FactoryGirl.build(:jam_track_track, position: 1, jam_track: jam_track)
      jam_track_track_2.valid?.should == false
      #jam_track_track_2.errors[:position].should == ['has already been taken']
    end

    it "jam_track required" do
      pending "Need to be not mandatory because of activeadmin"
      jam_track = FactoryGirl.build(:jam_track_track, jam_track: nil)
      jam_track.valid?.should be_false
      jam_track.errors[:jam_track].should == ["can't be blank"]
    end
  end


  describe "upload/download" do
    TRACK_NAME = 'lead guitar.ogg'

    in_directory_with_file(TRACK_NAME)

    before(:all) do
      original_storage = JamTrackTrackUploader.storage = :fog
    end

    after(:all) do
      JamTrackTrackUploader.storage = @original_storage
    end

    before(:each) do
      content_for_file('abc')
    end

    it "uploads to s3 with correct name, and then downloads via signed URL" do
      s3 = S3Manager.new(APP_CONFIG.aws_bucket, APP_CONFIG.aws_access_key_id, APP_CONFIG.aws_secret_access_key)

      jam_track_track = FactoryGirl.create(:jam_track_track)
      s3.upload(jam_track_track.manually_uploaded_filename(:url_48), TRACK_NAME)
      jam_track_track[:url_48] = jam_track_track.manually_uploaded_filename(:url_48)
      jam_track_track.save!
      jam_track_track.reload

      # verify that the uploader stores the correct path
      jam_track_track[:url_48].should == jam_track_track.manually_uploaded_filename(:url_48)

      # verify it's on S3
      s3.exists?(jam_track_track[:url_48]).should be_true
      s3.length(jam_track_track[:url_48]).should == 'abc'.length

      # download it via signed URL, and check contents
      url = jam_track_track.sign_url
      downloaded_contents = open(url).read
      downloaded_contents.should == 'abc'
    end

  end

end
