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 "namespam" do

    describe "no hostnames" do
      before {@user.first_name = "bleh www.something.com"}
      it { should_not be_valid }
    end

    describe "first name can't be mixed chinese" do
      before {@user.first_name = "注冊ww"}
      it { should_not be_valid }
    end

    describe "long chinese names" do
      before {@user.first_name = "注冊注冊注冊"; @user.last_name = "注冊"}
      it { should_not be_valid }
    end

    describe "if chinese first name, must be chinese last name" do
      before {@user.first_name = "注冊"; @user.last_name = "abc"}
      it { should_not be_valid }
    end

    describe "chinese names can be allchinese" do
      before {@user.first_name = "注冊"; @user.last_name = "注冊"}
      it { puts @user.errors.inspect; should be_valid }
    end

    describe "no hostname-looking stuff - first name" do
      before {@user.first_name = "www server com"}
      it { should_not be_valid }
    end

    describe "no hostname-looking stuff - last name" do
      before {@user.first_name = "www server com"}
      it { should_not be_valid }
    end

    describe "no junk characters" do
      before {@user.first_name = "name.come"}
      it { should_not be_valid }
    end

    describe "no junk characters - period" do
      before {@user.first_name = "name.come"}
      it { should_not be_valid }
    end

    describe "no junk characters - percent" do
      before {@user.first_name = "name%"}
      it { should_not be_valid }
    end

    describe "no junk characters - amp" do
      before {@user.first_name = "name&"}
      it { should_not be_valid }
    end

    describe "no junk characters - asterisk" do
      before {@user.first_name = "name*"}
      it { should_not be_valid }
    end
  end


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

  describe "when last name is not present" do
    before { @user.last_name = " " }
    it { should 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_confirmation].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
      # too short
      @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_confirmation].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
      pending "Restore jamkazam test account in Recurly"
      @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 "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 == nil
    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 == {}
    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}}

    end

    it "allow no_show aggr  egation" 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}}
    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}}
    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

  describe "sync_stripe_customer" do
    let(:user) { FactoryGirl.create(:user) }
    let(:token1) { create_stripe_token }
    let(:token2) { create_stripe_token(2018) }

    before {
      pending "Lessons paused"
    }

    # possible Stripe::InvalidRequestError
    it "reuses user on card update" do
      user.stripe_customer_id.should be_nil
      user.payment_update({stripe_token: token1})
      user.reload
      user.stripe_customer_id.should_not be_nil
      customer1 = user.stripe_customer_id

      # let's change email address too
      user.email = 'unique+1@jamkazam.com'
      user.save!

      token2.should_not eql token1
      user.payment_update({stripe_token: token2})
      user.reload
      user.stripe_customer_id.should_not be_nil
      customer2 = user.stripe_customer_id

      customer1.should eql customer2
      # double-check that the stripe customer db record got it's email synced
      customer = user.fetch_stripe_customer
      customer.email.should eql 'unique+1@jamkazam.com'

    end
  end

  describe "can_buy_test_drive?" do
    let(:user) { FactoryGirl.create(:user) }
    after {
      Timecop.return
    }
    it "works" do
      user.can_buy_test_drive?.should be true
      FactoryGirl.create(:test_drive_purchase, user: user)
      user.can_buy_test_drive?.should be false
      Timecop.freeze(Date.today + 366)
      user.can_buy_test_drive?.should be true
    end
  end

  describe "has_rated_teacher" do

    before {
      pending "Lessons paused"
    }

    let(:user) { FactoryGirl.create(:user) }
    let(:teacher) { FactoryGirl.create(:teacher) }
    it "works" do
      user.has_rated_teacher(teacher).should eql false
      review = Review.create(target:teacher, rating:3, user: user)
      review.errors[:target].should eql ["You must have at least scheduled or been in a lesson with this teacher"]
      normal_lesson(user, teacher.user)
      review = Review.create(target:teacher, rating:3, user: user)
      review.errors.any?.should be false
      user.has_rated_teacher(teacher).should be true
    end
  end

  describe "recent_test_drive_teachers" do
    before {
      pending "Lessons paused"
    }
    let(:user) { FactoryGirl.create(:user) }
    let(:teacher) { FactoryGirl.create(:teacher_user) }
    it "works" do
      user.recent_test_drive_teachers.all.length.should eql 0

      testdrive_lesson(user, teacher)

      user.recent_test_drive_teachers[0].id.should eql teacher.id

    end
  end

  describe "update_name" do

    let(:user) {FactoryGirl.create(:user)}

    it "typical 2 bits" do
      user.update_name("Seth Call")
      user.errors.any?.should be_false
      user.reload
      user.first_name.should eql 'Seth'
      user.last_name.should eql 'Call'
    end
  end

  describe "uncollectables" do
    let(:user) {FactoryGirl.create(:user)}
    let(:teacher) {FactoryGirl.create(:teacher_user)}

    before(:each) do
      pending "Lessons paused"
    end

    it "empty" do
      user.uncollectables.count.should eql 0
    end

    it "one" do
      lesson_session = normal_lesson(user, teacher)
      lesson_session.lesson_payment_charge.user.should eql user
      lesson_session.lesson_payment_charge.billing_attempts = 1
      lesson_session.lesson_payment_charge.save!
      uncollectables = user.uncollectables
      uncollectables.count.should eql 1
      uncollectable = uncollectables[0]
      uncollectable.description.should_not be_nil
      uncollectable.expected_price_in_cents.should eql 3000
      uncollectable.is_card_declined?.should be_false
    end

    it "for monthly" do
      Timecop.travel(Date.new(2016,1,1))
      lesson_session = monthly_lesson(user, teacher)
      lesson_session.booked_price.should eql 30.00
      LessonBooking.hourly_check
      lesson_session.lesson_payment_charge.should be_nil
      purchases=LessonPackagePurchase.where(user_id: user.id)
      purchases.count.should eql 1
      purchases[0].lesson_payment_charge.billed = false
      purchases[0].lesson_payment_charge.billing_attempts = 1
      purchases[0].lesson_payment_charge.save!
      uncollectables = user.uncollectables
      uncollectables.count.should eql 1
      uncollectable = uncollectables[0]
      uncollectable.description.should_not be_nil
      uncollectable.expected_price_in_cents.should eql 3000
      uncollectable.is_card_declined?.should be_false
    end

    it "for monthly near end of month" do
      Timecop.travel(Date.new(2016,5,23))
      lesson_session = monthly_lesson(user, teacher)
      lesson_session.booked_price.should eql 30.00
      LessonBooking.hourly_check
      lesson_session.lesson_payment_charge.should be_nil
      purchases=LessonPackagePurchase.where(user_id: user.id)
      purchases.count.should eql 1
      purchases[0].lesson_payment_charge.billed = false
      purchases[0].lesson_payment_charge.billing_attempts = 1
      purchases[0].lesson_payment_charge.save!
      uncollectables = user.uncollectables
      uncollectables.count.should eql 1
      uncollectable = uncollectables[0]
      uncollectable.description.should_not be_nil
      uncollectable.expected_price_in_cents.should eql 750
      uncollectable.is_card_declined?.should be_false
    end
  end
  describe "handle_test_drive_package" do
    let(:user) {FactoryGirl.create(:user)}

    it "4-count" do
      package_size = 4
      package = FactoryGirl.create(:test_drive_package, :four_pack)
      detail = {}
      teachers = []
      detail[:teachers] = teachers
      package.test_drive_package_teachers.each do |package_teacher|
        teachers << {id: package_teacher.user.id}
      end
      user.handle_test_drive_package(package, detail)

      user.errors.any?.should be_false

      LessonSession.where(user_id: user.id).count.should eql package_size
      user.student_lesson_bookings.count.should eql package_size
      user.student_lesson_bookings.each do |booking|
        booking.status.should eql LessonBooking::STATUS_REQUESTED
        booking.card_presumed_ok.should be_false
      end
    end
  end
  describe "onboarding_status" do
    let(:user) {FactoryGirl.create(:user)}

    before(:each) {UserMailer.deliveries.clear}

    it "onboarded" do
      user.send_onboarding_survey.should be_false
      user.onboarding_onboarded_at = Time.now
      user.save!
      user.reload
      user.send_onboarding_survey.should be_true
      UserMailer.deliveries.count.should eql 1
      user.onboarding_status = User::ONBOARDING_STATUS_ONBOARDED
    end

    it "lost" do
      user.send_onboarding_survey.should be_false
      user.onboarding_lost_reason = User::LOST_REASON_NO_VIDEO_STREAM
      user.save!
      user.reload
      user.send_onboarding_survey.should be_true
      UserMailer.deliveries.count.should eql 0
      user.onboarding_status = User::ONBOARDING_STATUS_LOST
    end

    it "escalated" do
      user.send_onboarding_survey.should be_false
      user.onboarding_escalation_reason = User::ESCALATION_REASON_NO_VIDEO_STREAM
      user.save!
      user.reload
      user.send_onboarding_survey.should be_true
      UserMailer.deliveries.count.should eql 0
      user.onboarding_status = User::ONBOARDING_STATUS_ESCALATED
    end

    it "taken free lesson" do
      user.send_onboarding_survey.should be_false
      user.first_onboarding_free_lesson_at = Time.now
      user.save!
      user.reload
      user.send_onboarding_survey.should be_false
      UserMailer.deliveries.count.should eql 0
      user.onboarding_status = User::ONBOARDING_STATUS_FREE_LESSON
    end

    it "paid lesson" do
      user.send_onboarding_survey.should be_false
      user.first_onboarding_paid_lesson_at = Time.now
      user.save!
      user.reload
      user.send_onboarding_survey.should be_false
      UserMailer.deliveries.count.should eql 0
      user.onboarding_status = User::ONBOARDING_STATUS_PAID_LESSON
    end

    it "assigned" do
      user.send_onboarding_survey.should be_false
      user.onboarder = FactoryGirl.create(:user, is_onboarder:true)
      user.save!
      user.reload
      user.send_onboarding_survey.should be_false
      UserMailer.deliveries.count.should eql 1
      user.onboarding_status = User::ONBOARDING_STATUS_ASSIGNED
    end

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

    it "works" do
      UserMailer.deliveries.clear
      user.send_onboarding_survey = true
      user.save!

      User.send_onboarding_surveys

      UserMailer.deliveries.count.should eql 1
      user.reload
      user.send_onboarding_survey.should be_true
      user.sent_onboarding_survey_at.should_not be_nil

      UserMailer.deliveries.clear
      User.send_onboarding_surveys
      UserMailer.deliveries.count.should eql 0
    end
  end


  describe "send_take_lesson_poke" do
    let(:user) {FactoryGirl.create(:user)}
    before(:each) {
      UserMailer.deliveries.clear
    }
    after {
      Timecop.return
    }

    it "works" do

      teacher = FactoryGirl.create(:teacher, ready_for_session_at: Time.now)
      
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear

      user.touch
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear

      posa_card = FactoryGirl.create(:amazon_test_drive_free_2)
      posa_card.claim(user)

      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear

      Timecop.freeze(2.hours.from_now)
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 1
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 1
      user.remind_take_lesson_at.should_not be_nil


      # no shift in time, so, no new one
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 1
      user.remind_take_lesson_at.should_not be_nil

      # jump 3 days in future
      Timecop.freeze(3.days.from_now)
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 1
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 2
      user.remind_take_lesson_at.should_not be_nil

      # no shift in time, so, no new one
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 2
      user.remind_take_lesson_at.should_not be_nil

      # jump 3 days in future
      Timecop.freeze(3.days.from_now)
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 1
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 3
      user.remind_take_lesson_at.should_not be_nil


      # no shift in time, so, no new one
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 3
      user.remind_take_lesson_at.should_not be_nil

      # jump 3 days in future
      Timecop.freeze(3.days.from_now)
      User.send_take_lesson_poke
      UserMailer.deliveries.count.should eql 0
      UserMailer.deliveries.clear
      user.reload
      user.remind_take_lesson_times.should eql 3
      user.remind_take_lesson_at.should_not be_nil
    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
