# this is not a jam session - this is an 'auth session'
class SessionsController < ApplicationController

  def new
    @login_error = false
    render :layout => "landing"
  end

  def create
    user = User.authenticate(params[:session][:email], params[:session][:password])

    if user.nil?
      @login_error = true
      render 'new', :layout => "landing"
    else

      if jkclient_agent?
        user.update_progression_field(:first_ran_client_at)
      end

      @session_only_cookie = !jkclient_agent? && !params[:user].nil? && 0 == params[:user][:remember_me].to_i
      complete_sign_in user
    end
  end

# OAuth docs
# http://net.tutsplus.com/tutorials/ruby/how-to-use-omniauth-to-authenticate-your-users/
  def create_oauth
    auth_hash = request.env['omniauth.auth']
    authorization = UserAuthorization.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
    if authorization
      # Sign in for a user who has already registered.
      complete_sign_in authorization.user
    else
      # Sign up for a completely new user.
      # First/last name: auth_hash["info"]["first_name"] and auth_hash["info"]["last_name"]
      # token: auth_hash["credentials"]["token"] -- "expires_at"
      #
      # For debugging - to see what all is there:
      # render :text => auth_hash.to_yaml
      #FbGraph.debug!
      #app = FbGraph::Application.new  '468555793186398', :secret => '546a5b253972f3e2e8b36d9a3dd5a06e'
      token = auth_hash[:credentials][:token]

      # FIXME:
      # This should probably be in a transaction somehow, meaning the user 
      # create and the authorization create. Concern is UserManager.new.signup sends
      # an email and whatnot.
      #
      # Also, should we grab their photo from facebook?
      user = UserManager.new.signup(remote_ip(),
                                    auth_hash[:info][:first_name],
                                    auth_hash[:info][:last_name],
                                    auth_hash[:info][:email],
                                    nil,
                                    nil,
                                    nil, # instruments
                                    nil, # photo_url
                                    nil)
                              
      # Users who sign up using oauth are presumed to have valid email adddresses.
      user.confirm_email!
      
      auth = user.user_authorizations.build :provider => auth_hash[:provider], 
                                            :uid => auth_hash[:uid], 
                                            :token => auth_hash[:credentials][:token], 
                                            :token_expiration => Time.at(auth_hash[:credentials][:expires_at])
      user.save
      complete_sign_in user
    end
  end

  
  def oauth_callback
    if current_user.nil?
      render :nothing => true, :status => 404
      return
    end

    auth_hash = request.env['omniauth.auth']
    #authorization = UserAuthorization.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])

    # Always make and save a new authorization. This is because they expire, and honestly there's no cost
    # to just making and saving it.
    #if authorization.nil?
      authorization = current_user.user_authorizations.build :provider => auth_hash[:provider], 
                                                             :uid => auth_hash[:uid], 
                                                             :token => auth_hash[:credentials][:token], 
                                                             :token_expiration => Time.at(auth_hash[:credentials][:expires_at])
      authorization.save
    #end

    render 'oauth_complete', :layout => "landing"
  end

  def complete_sign_in(user)
    sign_in user

    if !params[:sso].nil? && params[:sso] == "desk"
      # generate multipass token and sign it
      multipass = DeskMultipass.new(user)
      callback_url = SampleApp::Application.config.multipass_callback_url
      redirect_to "#{callback_url}?multipass=#{multipass.token}&signature=#{multipass.signature}"
    else
      redirect_back_or client_url
    end
  end

  def destroy
    # earlier, code here would delete the connection using client_id  from cookies
    # however, we should never try to delete the client_id cookie (make it as permanent as possible)
    # also, because the client will stop heartbeating and close the connection to gateway,
    # in any case the server will notice after 10 seconds that the user is gone.
    # if we really want someone to know right away that the client is gone, then just make sure the client calls
    # leave session before it calls delete (VRFS-617 should solve that)
    sign_out
    redirect_to client_url
  end

  def failure

  end

  def connection_state
    if (defined?(TEST_CONNECT_STATES) && TEST_CONNECT_STATES) || 'development'==Rails.env
      @prefix = defined?(TEST_CONNECT_STATE_JS_LOG_PREFIX) ? TEST_CONNECT_STATE_JS_LOG_PREFIX : '*** '
      render('connection_state', :layout => 'client') && return
    end
    render :nothing => true, :status => 404
  end

end
