module SessionsHelper

  def sign_in(user)
    set_remember_token(user)
    self.current_user = user
  end

  def set_remember_token(user)
    if @session_only_cookie
      cookies.delete(:remember_token)
      cookies[:remember_token] = user.remember_token
    else
      cookies[:remember_token] = {
        :value => user.remember_token,
        :expires => 20.years.from_now.utc
      }
    end
  end

  def signed_in?
    !current_user.nil?
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def current_user?(user)
    user == current_user
  end

  def signed_in_user
    unless signed_in?
      store_location
      redirect_to signin_url, notice: "Please sign in."
    end
  end


  def api_signed_in_user
    unless signed_in?
      render :json => {}, :status => 403
    end
  end

  def sign_out
    current_user = nil
    cookies.delete(:remember_token)
  end

  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end

  def store_location
    session[:return_to] = request.url
  end

  def jkclient_agent?
    request.env['HTTP_USER_AGENT'] =~ /JamKazam/
  end

  # used to help GA tracking.  should result in one of Visitor, Registered User, or Paying Subscriber
  def ga_user_level
    if current_user.nil?
      'Visitor'
    else
      'Registered User'  # TODO: when paying subscriber exists, add to it
    end
  end

  # used to help GA tracking.  should result in either Fan or Musician
  def ga_user_type
    if current_user.nil?
      'Fan'
    else
      current_user.musician? ? 'Musician' : 'Fan'
    end
  end
end
