require "#{File.dirname(__FILE__)}/../test_helper"

class GuestReaderTest < ActionController::IntegrationTest
  
  fixtures :users, :topics, :comments, :settings, :readings
  
  def test_keep_same_guest_account
    # get the front page
    get "/"
    assert_response :success
    # is a guest user
    assert guest_user?
    original_guest_account_id = session[:user]
    
    get topic_url(:id => 1)
    assert_response :success
    assert guest_user?
    assert_equal original_guest_account_id, session[:user]
  end
  
  def test_login
    post login_url(:email => users(:quentin).email, :password => users(:quentin).password)
    assert_response :redirect
    assert session[:user]
    follow_redirect!
    assert session[:user]
    assert_equal users(:quentin).id, session[:user]
  end
  
  def test_guest_login
    unregistered_user_reads_two_comments
    guest_id = session[:user]
    assert_equal 2, User.find(guest_id).readings.count

    # login as a registered user
    get login_url
    assert_equal 0, users(:quentin).readings.count
    post login_url(:email => users(:quentin).email, :password => users(:quentin).password)
    
    follow_redirect!
    
    assert_equal users(:quentin).id, session[:user]
    # should have readings from when reading as a guest
    assert_equal 2, users(:quentin).readings.count
    # guest should be removed
    assert_record_not_found(User, guest_id)
  end
  
  def test_guest_registers
    unregistered_user_reads_two_comments 
    guest_id = session[:user]
    
    # register new account
    get register_url
    assert_response :success
    
    post register_url, :user => { :email => 'quire@example.com', 
                                  :password => 'quyre', 
                                  :name => 'Jeremy',
                                  :password_confirmation => 'quyre',
                                  :user_number => '392109',
                                  :postal_code => 'k1r',
                                  :year_of_birth => '1970',
                                  :gender => 1 }
    assert_response :redirect
    follow_redirect!
    
    assert session[:user] != guest_id
    # should have readings from when reading as a guest
    assert_equal 2, User.find(session[:user]).readings.count
    # guest should be removed
    assert_record_not_found(User, guest_id)
  end
  
  private
  
    def guest_user?
      session[:user] && User.find(session[:user]).is_a?(Guest)
    end
    
    def read_comment(id)
      xml_http_request(comment_read_url(:id => id))
    end
    
    def unregistered_user_reads_two_comments
      get topic_url(:id => 1)
      read_comment(comments(:long_first_post))
      read_comment(comments(:second_reply))
    end
end