require 'spec_helper'

RESET_PASSWORD_URL = "/reset_token"

describe User do

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

  subject { @user }

  it { should respond_to(:first_name) }
  it { should respond_to(:last_name) }
  it { should respond_to(:email) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  it { should respond_to(:remember_token) }
  it { should respond_to(:admin) }
  it { should respond_to(:valid_password?) }
  it { should respond_to(:can_invite) }

  it { should be_valid }
  it { 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 "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 "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.]
      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
      @user.email = mixed_case_email
      @user.save!
      @user.reload.email.should == mixed_case_email
    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
    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", "USA", 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", "USA", 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
        @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

=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
