require 'spec_helper'
require 'jam_ruby/recurly_client'

RESET_PASSWORD_URL = "/reset_token"

describe User do

  before do
    User.delete_all
    @user = User.new(first_name: "Example", last_name: "User", email: "user@example.com",
                     password: "foobar", password_confirmation: "foobar", city: "Apex", state: "NC", country: "US", terms_of_service: true, musician: true)
    @user.musician_instruments << FactoryGirl.build(:musician_instrument, player: @user)
    @recurly = RecurlyClient.new
  end

  subject { @user }

  it {
    should respond_to(:first_name)
    should respond_to(:last_name)
    should respond_to(:email)
    should respond_to(:password)
    should respond_to(:password_confirmation)
    should respond_to(:remember_token)
    should respond_to(:admin)
    should respond_to(:valid_password?)
    should respond_to(:can_invite)
    should respond_to(:mods)
    should respond_to(:last_jam_audio_latency)
    should respond_to(:website)
    should respond_to(:age)
    should respond_to(:skill_level)
    should respond_to(:concert_count)
    should respond_to(:studio_session_count)
    should respond_to(:virtual_band)
    should respond_to(:virtual_band_commitment)
    should respond_to(:traditional_band)
    should respond_to(:traditional_band_commitment)
    should respond_to(:traditional_band_touring)
    should respond_to(:paid_sessions)
    should respond_to(:paid_sessions_hourly_rate)
    should respond_to(:paid_sessions_daily_rate)
    should respond_to(:free_sessions)
    should respond_to(:cowriting)
    should respond_to(:cowriting_purpose)
    should be_valid
    should_not be_admin
  }

  describe "accessible attributes" do
    it "should not allow access to admin" do
      userish = User.new(admin: true)
      userish.admin.should == false # the .new style above will be ignored
      userish.admin = true # but deliberate property setting will work
      userish.admin.should == true
    end
  end

  describe "stats" do

    it "no user" do
      stats = User.stats
      stats['musicians'].should == 0
      stats['fans'].should == 0
      stats['downloaded_client'].should == 0
      stats['ran_client'].should == 0
      stats['certified_gear'].should == 0
      stats['invited'].should == 0
      stats['friended'].should == 0
      stats['social_promoted'].should == 0
      stats['audio_latency_avg'].should == 0
    end

    it "single user" do
      @user.musician = true
      @user.last_jam_audio_latency = 5
      @user.save!
      stats = User.stats
      @user.musician.should be_true
      stats['musicians'].should == 1
      stats['fans'].should == 0
      stats['downloaded_client'].should == 0
      stats['ran_client'].should == 0
      stats['certified_gear'].should == 0
      stats['invited'].should == 0
      stats['friended'].should == 0
      stats['social_promoted'].should == 0
      stats['audio_latency_avg'].should == 5
    end
  end

  describe "with admin attribute set to 'true'" do
    before do
      @user.save!
      @user.toggle!(:admin)
    end

    it { should be_admin }
  end
  

  describe "when first name is not present" do
    before { @user.first_name = " " }
    it { should_not be_valid }
  end

  describe "when last name is not present" do
    before { @user.last_name = " " }
    it { should_not be_valid }
  end

  describe "when email is not present" do
    before { @user.email = " " }
    it { should_not be_valid }
  end

  describe "when first name is too long" do
    before { @user.first_name = "a" * 51 }
    it { should_not be_valid }
  end

  describe "when last name is too long" do
    before { @user.last_name = "a" * 51 }
    it { should_not be_valid }
  end

  describe "when mods is null" do
    before { @user.mods = nil }
    it { should be_valid }
  end


  describe "when mods is json object" do
    before { @user.mods = '{"no_show":{"value": true}}' }
    it { should be_valid }
  end



  describe "first or last name cant have profanity" do
    it "should not let the first name have profanity" do
      @user.first_name = "fuck you"
      @user.save
      @user.should_not be_valid
    end
    
    it "should not let the last name have profanity" do
      @user.last_name = "fuck you"
      @user.save
      @user.should_not be_valid
    end
  end

  describe "when email format is invalid" do
    it "should be invalid" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo. blah@gmail..com]
      addresses.each do |invalid_address|
        @user.email = invalid_address
        @user.should_not be_valid
      end
    end
  end

  describe "when email format is valid" do
    it "should be valid" do
      addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
      addresses.each do |valid_address|
        @user.email = valid_address
        @user.should be_valid
      end
    end
  end

  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.email = @user.email.upcase
      user_with_same_email.save
    end

    it { should_not be_valid }
  end

  describe "email address with mixed case" do
    let(:mixed_case_email) { "Foo@ExAMPle.CoM" }


    it "should be saved as all lower-case" do
      pending
      @user.email = mixed_case_email
      @user.save!
      @user.reload.email.should == mixed_case_email.downcase
    end
  end

  describe "when password is not present" do
    before { @user.password = @user.password_confirmation = " " }
    it { should_not be_valid }
  end

  describe "when password doesn't match confirmation" do
    before { @user.password_confirmation = "mismatch" }
    it { should_not be_valid }
  end

  describe "when password confirmation is nil" do
    before { @user.password_confirmation = nil }
    it { should_not be_valid }
  end

  describe "with a password that's too short" do
    before { @user.password = @user.password_confirmation = "a" * 5 }
    it { should be_invalid }
  end


  describe "set_password" do
    before do
      @user.confirm_email!
      @user.save.should be_true
      UserMailer.deliveries.clear
    end

    it "setting a new password should work" do
      @user.set_password("foobar", "newpassword", "newpassword")
      User.authenticate(@user.email, "newpassword").should_not be_nil
      UserMailer.deliveries.length.should == 1
    end
    
    it "setting a new password should fail if old one doesnt match" do
      @user.set_password("wrongold", "newpassword", "newpassword")
      @user.errors.any?.should be_true
      @user.errors[:current_password].length.should == 1
      UserMailer.deliveries.length.should == 0
    end

    it "setting a new password should fail if new ones dont match" do
      @user.set_password("foobar", "newpassword", "newpassword2")
      @user.errors.any?.should be_true
      @user.errors[:password].length.should == 1
      UserMailer.deliveries.length.should == 0
    end
    
    it "setting a new password should fail if new one doesnt validate" do
      @user.set_password("foobar", "a", "a")
      @user.errors.any?.should be_true
      @user.errors[:password].length.should == 1
      UserMailer.deliveries.length.should == 0
    end

    it "setting a new password should fail if the new one is null" do
      @user.set_password("foobar", nil, nil)
      @user.errors.any?.should be_true
      @user.errors[:password].length.should == 1
      UserMailer.deliveries.length.should == 0
    end
    
  end
  
  describe "reset_password" do
    before do
      @user.confirm_email!
      @user.save
    end
    
    it "fails if the provided email address is unrecognized" do
      expect { User.reset_password("invalidemail@invalid.com", RESET_PASSWORD_URL) }.to raise_error(JamRuby::JamArgumentError)
    end

    it "assigns a reset_token and reset_token_created on reset" do
      User.reset_password(@user.email, RESET_PASSWORD_URL)
      @user.reload
      @user.reset_password_token.should_not be_nil
      @user.reset_password_token_created.should_not be_nil
      @user.reset_password_token_created.should <= Time.now
      @user.reset_password_token_created.should >= Time.now - 1.minute
    end

    it "errors if the wrong token comes in" do
      User.reset_password(@user.email, RESET_PASSWORD_URL)
      @user.reload
      expect { User.set_password_from_token(@user.email, "wrongtoken", "newpassword", "newpassword") }.to raise_error
    end

    it "changes the password if the token is right" do
      User.reset_password(@user.email, RESET_PASSWORD_URL)
      @user.reload
      User.set_password_from_token(@user.email, @user.reset_password_token, "newpassword", "newpassword")
      User.authenticate(@user.email, "newpassword").should_not be_nil
      @user.reload
    end
  end

  describe "return value of authenticate method" do
    before { @user.save }
    let(:found_user) { User.find_by_email(@user.email) }

    describe "with valid password" do
      it { found_user.valid_password?(@user.password).should be_true }
    end

    describe "with invalid password" do
      let(:user_for_invalid_password) { found_user.valid_password?("invalid") }

      it { should_not == user_for_invalid_password }
      specify { user_for_invalid_password.should be_false }
    end
  end

  describe "remember token" do
    before { @user.save }
    its(:remember_token) { should_not be_blank }
  end

  describe "user progression only touches once" do
    it "allows first touch" do
      @user.update_progression_field (:first_downloaded_client_at)
      @user.errors.any?.should be_false
      @user.first_downloaded_client_at.should_not be_nil
    end

    it "ignores second touch" do
      time = DateTime.now - 1
      @user.update_progression_field(:first_downloaded_client_at, time)
      first_value = @user.first_downloaded_client_at
      @user.update_progression_field(:first_downloaded_client_at)
      @user.errors.any?.should be_false
      @user.first_downloaded_client_at.should == first_value
    end
  end

  describe "authenticate (class-instance)" do
    before { @user.email_confirmed=true; @user.save }
    
    describe "with valid password" do
      it { should == User.authenticate(@user.email, @user.password) }
    end

    describe "with invalid password" do
      it { User.authenticate(@user.email, "invalid").should be_nil }
    end

    describe "with invalid email" do
      it { User.authenticate("junk", "invalid").should be_nil }
    end

    describe "with nil args" do
      it { User.authenticate(nil, nil).should be_nil }
    end

    describe "with empty args" do
      it { User.authenticate("", "").should be_nil }
    end
  end

  describe "create_dev_user" do
    before { @dev_user = User.create_dev_user("Seth", "Call", "seth@jamkazam.com", "Jam123", "Austin", "Texas", "US", nil, nil)  }

    subject { @dev_user }

    describe "creates a valid record" do
      it { should be_valid }
    end

    describe "should not be a new record" do
      it { should be_persisted }
    end
    
    describe "updates record" do
      before { @dev_user = User.create_dev_user("Seth", "Call2", "seth@jamkazam.com", "Jam123", "Austin", "Texas", "US", nil, nil) }

      it { should be_valid }

      its(:last_name) { should == "Call2" }

    end
  end

  describe "update email" do

    before do
      UserMailer.deliveries.clear
    end

    describe "begin email update" do
      describe "success" do
        before do
          @user.begin_update_email("somenewemail@blah.com", "foobar", "http://www.jamkazam.com/confirm_email_update?token=")
        end

        # useful to see contents of email without actually running the app and sending it
        it { @user.errors.any?.should be_false }
        it { @user.update_email.should == "somenewemail@blah.com" }
        it { @user.update_email_confirmation_url.should == "http://www.jamkazam.com/confirm_email_update?token=#{@user.update_email_token}" }
        it { UserMailer.deliveries.length.should == 1 }

      end

      it "no email on error" do
        @user.begin_update_email("somenewemail@blah.com", "wrong password", "http://www.jamkazam.com/confirm_email_update?token=")

        UserMailer.deliveries.length.should == 0
      end

      it "bad password validation" do
        @user.begin_update_email("somenewemail@blah.com", "wrong password", "http://www.jamkazam.com/confirm_email_update?token=")

        @user.errors[:current_password][0].should == ValidationMessages::NOT_YOUR_PASSWORD
      end

      it "matches current email" do
        @user.begin_update_email(@user.email, "foobar", "http://www.jamkazam.com/confirm_email_update?token=")

        @user.errors[:update_email][0].should == ValidationMessages::EMAIL_MATCHES_CURRENT
      end

      it "existing email of another user" do
        another_user = FactoryGirl.create(:user)
        @user.begin_update_email(another_user.email, "foobar", "http://www.jamkazam.com/confirm_email_update?token=")

        @user.errors[:update_email][0].should == ValidationMessages::EMAIL_ALREADY_TAKEN
      end

      it "bogus email" do
        @user.begin_update_email("not_an_email", "foobar", "http://www.jamkazam.com/confirm_email_update?token=")

        @user.errors[:update_email][0].should == "is invalid"
      end

      it "empty email" do
        @user.begin_update_email(nil, "foobar", "http://www.jamkazam.com/confirm_email_update?token=")

        @user.errors[:update_email][0].should == "can't be blank"
      end
    end

    describe "finalize email update" do
      before do
        @recurly.has_account?(@user).should == false

        @user.begin_update_email("somenewemail@blah.com", "foobar", "http://www.jamkazam.com/confirm_email_update?token=")
        UserMailer.deliveries.clear
      end

      describe "success" do

        before do
          @finalized = User.finalize_update_email(@user.update_email_token)
        end

        it { @finalized.should == @user }
        it { @finalized.email.should == "somenewemail@blah.com" }
        it { UserMailer.deliveries.length.should == 1 }
      end

      it "no email on unsuccessful finalize" do
        expect { User.finalize_update_email("wrong_token") }.to raise_error(ActiveRecord::RecordNotFound)
        UserMailer.deliveries.length.should == 0
      end

      it "bad token" do
        expect { User.finalize_update_email("wrong_token") }.to raise_error(ActiveRecord::RecordNotFound)
      end

      it "empty token" do
        expect { User.finalize_update_email(nil) }.to raise_error(ActiveRecord::RecordNotFound)
      end
    end
  end

  describe "finalize email updates recurly" do
    before do
      
      @user.begin_update_email("somenewemail@blah.com", "foobar", "http://www.jamkazam.com/confirm_email_update?token=")
      UserMailer.deliveries.clear
      billing_info = {
        first_name: @user.first_name,
        last_name: @user.last_name,
        address1: 'Test Address 1',
        address2: 'Test Address 2',
        city: @user.city,
        state: @user.state,
        country: @user.country,
        zip: '12345',
        number: '4111-1111-1111-1111',
        month: '08',
        year: '2017',
        verification_value: '111'
      }
      @recurly.find_or_create_account(@user, billing_info)
    end

    it "should update recurly" do
      @recurly.has_account?(@user).should == true
      @recurly.get_account(@user).email.should_not == "somenewemail@blah.com"
      @finalized = User.finalize_update_email(@user.update_email_token)
      @recurly.get_account(@user).email.should == "somenewemail@blah.com"
    end        
  end

  describe "user_authorizations" do

    it "can create" do
      @user.user_authorizations.build  provider: 'facebook',
                                       uid: '1',
                                       token: '1',
                                       token_expiration: Time.now,
                                       user: @user
      @user.save!
    end

    it "fails on duplicate" do
      @user.user_authorizations.build  provider: 'facebook',
                                       uid: '1',
                                       token: '1',
                                       token_expiration: Time.now,
                                       user: @user
      @user.save!

      @user2 = FactoryGirl.create(:user)
      @user2.user_authorizations.build  provider: 'facebook',
                                       uid: '1',
                                       token: '1',
                                       token_expiration: Time.now,
                                       user: @user2
      @user2.save.should be_false
      @user2.errors[:user_authorizations].should == ['is invalid']
    end


  end

  describe "mods" do
    it "should allow update of JSON" do
      @user.mods = {no_show: {something:1}}.to_json
      @user.save!
    end
  end

  describe "audio latency" do
    it "allow update" do
      @user.last_jam_audio_latency = 5
      @user.save!
    end

    it "prevent negative" do
      @user.last_jam_audio_latency = -1
      @user.save.should be_false
      @user.errors[:last_jam_audio_latency].should == ['must be greater than 2']
    end

    it "prevent non numerical" do
      @user.last_jam_audio_latency = 'a'
      @user.save.should be_false
      @user.errors[:last_jam_audio_latency].should == ['is not a number']
    end

    it "prevent 2 (minimum)" do
      @user.last_jam_audio_latency = User::MINIMUM_AUDIO_LATENCY
      @user.save.should be_false
      @user.errors[:last_jam_audio_latency].should == ['must be greater than 2']
    end

    it "prevent 10000 (maximum)" do
      @user.last_jam_audio_latency = User::MAXIMUM_AUDIO_LATENCY
      @user.save.should be_false
      @user.errors[:last_jam_audio_latency].should == ['must be less than 10000']
    end
  end

  describe "update_audio_latency" do

    before(:each) do
      @user.last_jam_audio_latency.should be_nil
    end

    it "ignores low latency" do
      @user.update_audio_latency(nil, User::MINIMUM_AUDIO_LATENCY)
      @user.last_jam_audio_latency.should be_nil
    end

    it "ignores high latency" do
      @user.last_jam_audio_latency.should be_nil
      @user.update_audio_latency(nil, User::MAXIMUM_AUDIO_LATENCY)
      @user.last_jam_audio_latency.should be_nil
    end

    it "accepts normal latency" do
      @user.last_jam_audio_latency.should be_nil
      @user.update_audio_latency(nil, User::MINIMUM_AUDIO_LATENCY + 1)
      @user.last_jam_audio_latency.should == User::MINIMUM_AUDIO_LATENCY + 1
    end
  end

  describe "html_sanitize" do
    it "sanitizes" do
      @user.first_name = '<b>first_name</b>'
      @user.last_name = '<i>last_name</i>'
      @user.biography = '<i>biography</b>'
      @user.country = '<a href="dog">country</a>'
      @user.state = '<table>state</table>'
      @user.city = '<barf>city</larf>'

      @user.save!
      @user.first_name.should == 'first_name'
      @user.last_name.should == 'last_name'
      @user.biography.should == 'biography'
      @user.country.should == 'country'
      @user.state.should == 'state'
      @user.city.should == 'city'
    end
  end

  describe "update_locidispids" do

    before(:each) do
      @user.save
      create_phony_database
    end

    after(:all) do
      create_phony_database
    end

    it "remains null if the user's last_jam_addr is null" do
      @user.last_jam_addr.should be_nil  # make sure the factory still makes a null addr to start
      User.update_locidispids(false)
      @user.reload
      @user.last_jam_addr.should be_nil
    end

    it "locidispid remains non-null and the same as before, if no maxmind info has changed" do
      @user.update_last_jam('1.1.1.1', User::JAM_REASON_REGISTRATION)
      initial_locidispid = @user.last_jam_locidispid
      initial_locidispid.should_not be_nil
      User.update_locidispids(false)
      @user.reload
      @user.last_jam_locidispid.should == initial_locidispid
      @user.last_jam_updated_reason.should == User::JAM_REASON_IMPORT
    end

    it "locidispid goes to null if geoip info is null" do
      @user.update_last_jam('1.1.1.1', User::JAM_REASON_REGISTRATION)
      initial_locidispid = @user.last_jam_locidispid
      initial_locidispid.should_not be_nil
      GeoIpBlocks.delete_all
      User.update_locidispids(false)
      @user.reload
      @user.last_jam_locidispid.should be_nil
      @user.last_jam_updated_reason.should == User::JAM_REASON_IMPORT
    end

    it "locidispid updates to a new value if geoip info changes" do
      @user.update_last_jam('1.1.1.1', User::JAM_REASON_REGISTRATION)
      initial_locidispid = @user.last_jam_locidispid
      initial_locidispid.should_not be_nil
      GeoIpBlocks.connection.execute("UPDATE geoipblocks SET locid = 17193::bigint where locid = 17192::bigint").check
      GeoIpLocations.connection.execute("UPDATE geoiplocations SET locid = 17193::bigint where locid = 17192::bigint").check
      GeoIpLocations.find_by_locid(17193).should_not be_nil
      GeoIpBlocks.find_by_locid(17193).should_not be_nil
      User.update_locidispids(false)
      @user.reload

      @user.last_jam_locidispid.should_not == initial_locidispid
      @user.last_jam_locidispid.should == 17193 * 1000000 + JamIsp.lookup(@user.last_jam_addr).coid

      @user.last_jam_updated_reason.should == User::JAM_REASON_IMPORT
    end

  end

  describe "recent history" do
    it "should only retrieve recordings with a claimed recording" do
      user = FactoryGirl.create(:user)
      claimed_recording = FactoryGirl.create(:claimed_recording, :user => user)
      claimed_recording.recording.owner = user
      claimed_recording.recording.save!

      recording = FactoryGirl.create(:recording, :owner => user)

      Recording.where(:owner_id => user.id).size.should == 2

      history = user.recent_history(nil, nil)
      history.size.should == 1
      history.first.id.should == claimed_recording.recording.id

      # exclude the claimed recording
      history = user.recent_history(nil, claimed_recording.id)
      history.size.should == 0
    end

    it "should not retrieve excluded session" do
      music_session = FactoryGirl.create(:music_session)
      history = music_session.creator.recent_history(nil, nil)
      history.size.should == 1

      history = music_session.creator.recent_history(music_session.id, nil)
      history.size.should == 0
    end
  end

  describe "age" do
    let(:user) {FactoryGirl.create(:user)}

    it "should calculate age based on birth_date" do
      user.birth_date = Time.now - 10.years
      user.age.should == 10

      user.birth_date = Time.now - 10.years + 3.months
      user.age.should == 9

      user.birth_date = nil
      user.age.should == ""
    end
  end

  describe "mods_merge" do
    let(:user) {FactoryGirl.create(:user)}

    it "allow empty merge" do
      user.mod_merge({})
      user.valid?.should be_true
      user.mods.should == {}.to_json
    end

    it "allow no_show set" do
      user.mod_merge({"no_show" => {"some_screen" => true}})
      user.valid?.should be_true
      user.mods.should == {no_show:{some_screen:true}}.to_json
    end

    it "allow no_show aggregation" do
      user.mod_merge({"no_show" => {"some_screen1" => true}})
      user.save!
      user.reload
      user.mod_merge({"no_show" => {"some_screen2" => true}})
      user.valid?.should be_true
      user.mods.should == {"no_show" => {"some_screen1" => true, "some_screen2" => true}}.to_json
    end

    it "allow no_show override" do
      user.mod_merge({"no_show" => {"some_screen1" => true}})
      user.save!
      user.reload
      user.mod_merge({"no_show" => {"some_screen1" => false}})
      user.valid?.should be_true
      user.mods.should == {no_show:{some_screen1:false}}.to_json
    end

    it "does not allow random root keys" do
      user.mod_merge({random_root_key:true})
      user.valid?.should be_false
      user.errors[:mods].should == [ValidationMessages::MODS_UNKNOWN_KEY]
    end

    it "does not allow non-hash no_show" do
      user.mod_merge({no_show:true})
      user.valid?.should be_false
      user.errors[:mods].should == [ValidationMessages::MODS_MUST_BE_HASH]
    end
  end

=begin
  describe "update avatar" do

    describe "success" do

      let(:s3_path) { "/public/avatars/#{@user.id}/avatar.jpg" }
      let(:original) { { "url" => "http://filepicker.io/blah", "key" => "/public/avatars/#{@user.id}/originals/avatar.jpg" } }
      let(:clipped) { { "url" => "http://filepicker.io/blah", "key" =>  s3_path } }

      before(:each) do
        @user.update_avatar(original, clipped, "jamkazam")
      end

      it { @user.errors.any?.should be_false }
      it { @user.original_fpfile.class == String }
      it { @user.cropped_fpfile.class == String }
      it { @user.photo_url = S3Util.url("jamkazam", s3_path, :secure => false ) }
    end

    describe "bad fpfiles" do
      let(:s3_path) { "/public/avatars/#{@user.id}/avatar.jpg" }
      let(:original) { { "url" => "http://filepicker.io/blah"  } } # take out 'key', which is required by model
      let(:clipped) { { "url" => "http://filepicker.io/blah", } } # take out 'key', which is required by model

      before(:each) do
        @user.update_avatar(original, clipped, "jamkazam")
      end

      it { @user.errors.any?.should be_true }
      it { @user.errors[:original_fpfile][0].should == ValidationMessages::INVALID_FPFILE }
      it { @user.errors[:cropped_fpfile][0].should == ValidationMessages::INVALID_FPFILE }
    end

  end
=end

end
