require 'spec_helper'

describe Mix do
  before do
    stub_const("APP_CONFIG", app_config)
    @user = FactoryGirl.create(:user)
    @connection = FactoryGirl.create(:connection, :user => @user)
    @instrument = FactoryGirl.create(:instrument, :description => 'a great instrument')
    @track = FactoryGirl.create(:track, :connection => @connection, :instrument => @instrument)
    @music_session = FactoryGirl.create(:active_music_session, :creator => @user, :musician_access => true)
    # @music_session.connections << @connection
    @music_session.save
    @connection.join_the_session(@music_session, true, nil, @user, 10)
    @recording = Recording.start(@music_session, @user)
    @recording.stop
	  @recording.claim(@user, "name", "description", Genre.first, true)
    @recording.errors.any?.should be_false
    @mix = Mix.schedule(@recording)
    @mix.reload
  end
 
  it "should create a mix for a user's recording properly" do
    @mix.recording_id.should == @recording.id
    @mix.mix_server.should be_nil
    @mix.started_at.should_not be_nil
    @mix.completed_at.should be_nil
  end

  it "should record when a mix has finished" do
    Mix.find(@mix.id).finish(10000, "md5hash", 10000, "md5hash")
    @mix.reload
    @mix.completed_at.should_not be_nil
    @mix.ogg_length.should == 10000
    @mix.ogg_md5.should == "md5hash"
  end

  it "create a good manifest" do
    Mix.find(@mix.id).finish(10000, "md5hash", 10000, "md5hash")
    @mix.reload
    manifest = @mix.manifest
    manifest["recording_id"].should == @recording.id
    manifest["files"].length.should == 1
  end

  it "signs url" do
    stub_const("APP_CONFIG", app_config)
    @mix.sign_url.should_not be_nil
  end

  it "mixes are restricted by user" do

    @mix.finish(1, "abc", 1, "def")
    @mix.reload
    @mix.errors.any?.should be_false

    @user2 = FactoryGirl.create(:user)

    recordings = Recording.list_downloads(@user)["downloads"]
    recordings.length.should == 1
    recordings[0][:type].should == "mix"
    recordings[0][:id].should == @mix.id.to_s

    recordings = Recording.list_downloads(@user2)["downloads"]
    recordings.length.should == 0
  end


  describe "download count" do
    it "will fail if too high" do
      mix = FactoryGirl.create(:mix)
      mix.current_user = mix.recording.owner
      mix.update_download_count(APP_CONFIG.max_audio_downloads + 1)
      mix.save
      mix.errors[:download_count].should == ["must be less than or equal to 100"]
    end
  end
end


