
step "there is no user information stored in the local storage" do
  visit empty_page_path
  page.execute_script %|Qstorage = window.localStorage|
  page.execute_script(%|Qstorage.removeItem('user_id')|)
  page.execute_script(%|Qstorage.removeItem('auth_token')|)
end

step "there is a user" do
  @user ||= create :user
end

step "there is a facebook user" do
  if @user
    raise "There already is a user, but not a facebook user"
  else
    @user ||= create :user, provider: 'facebook', uid: '123456790' # uid from spec_helper oauth setup
  end
end

step "there is a instagram user" do
  if @user
    raise "There already is a user, but not a instagram user"
  else
    @user ||= create :user, provider: 'instagram', uid: '123498765' # uid from spec_helper oauth setup
  end
end

step "the user is redirected to the sign in page" do
  when_ember_is_ready { ember_route_should_be '/sign-in' }
end

step "I am signed in as a user" do
  step "there is a user"
  visit test_login_admin_users_path(email: @user.email)
end

step "the user clicks the sign in via facebook button" do
  find('.sign-in-button.facebook').click
end

step "the user clicks the sign in via instagram button" do
  find('.sign-in-button.instagram').click
end
step "the user has no active session" do
  visit destroy_user_session_path
end

step "the user should be signed in as the facebook user" do
  @user = User.find_by_oauth_token 'fbAuthToken234'
  @user.should be_present
  # For now, actually better to test a signed in response from the server
  step "the newly created user info should be stored in the local storage"
end

step "the user should be signed in as the instagram user" do
  @user = User.find_by_oauth_token 'igAuthToken234'
  @user.should be_present
  # For now, actually better to test a signed in response from the server
  step "the newly created user info should be stored in the local storage"
end

step 'there is another signed in user user' do
  Capybara.session_name = :other_user
  step 'there is another user'
  visit test_login_admin_users_path(email: @other_user.email)
end

step "the user should be redirected to the homepage" do
  when_ember_is_ready { ember_route_should_be '/' }
end

step "the newly created user info should be stored in the local storage" do
  max_wait = 4
  time = 0.0
  time_step = 0.25
  user_id = page.evaluate_script(%|Qstorage.getItem('user_id')|)
  auth_token = page.evaluate_script(%|Qstorage.getItem('auth_token')|)
  while time < max_wait && user_id != @user.id && auth_token != @user.authentication_token
    time += time_step
    sleep time_step
    user_id = page.evaluate_script(%|Qstorage.getItem('user_id')|)
    auth_token = page.evaluate_script(%|Qstorage.getItem('auth_token')|)
  end
  user_id.should == @user.id
  auth_token.should == @user.authentication_token
end

step "the user authentication token changes" do
  @user ||= User.first
  @user.reset_authentication_token!
  @user.reload
end
