class UsersController < ApplicationController

  layout proc { false if request.xhr? }

  skip_before_filter :check_bank_account

  before_filter :require_student_or_tutor, only: [:dashboard, :upload_image , :update_billing_shipping_details]
  skip_before_filter :require_login , only: [:omniauth_create, :personal_calendar]

  # Get all information of current user to be displayed on dashboard.
  def index
    add_breadcrumb "Dashboard", :dashboard_path  if logged_in?
    add_breadcrumb "Search Results", :tutors_path
    if params[:search_type] == 'friends'
      @users = current_user.friends.page(params[:page]).per(params[:per_page])
    else
      @users = Tutor.search(params).page(params[:page]).per(params[:per_page]).records
    end
    @tutor_with_max_rate = Tutor.highest_rate.first
    @tutor_with_max_rating = Tutor.highest_reviewed.first
    respond_to do |format|
      format.html {render :layout => 'application' }
      format.js {render :layout => 'application' }
      format.json {render json: @users.except_user(current_user).to_json(only: :id, methods: [:full_name])}
    end
  end

  # Intialize new object for new user.
  def new
    if params[:type] != "tutor"
      type = "Student"
    else
      type = "Tutor"
    end
    @user = User.new(type: type, email: params[:email])
    if params[:invitation_token].present?
      @invite = Invite.find_by(invite_token: params[:invitation_token])
      @invite = Invite.find(params[:invite_id])
      @user.attributes = {email: @invite.invitee_email, invitation_token: @invite.invite_token}
    end
    render layout: (request.xhr? ? false : 'profile')
  end

  def select_user_type
    render layout: (request.xhr? ? false : 'profile')
  end

  # Get all user information by Id.
  def show
    @user = User.find(params[:id])
    render layout: false
  end

  # Used to redirect the user to linkedin or facebook when user click signup through linkedin or facebook respectively.
  def oauth
    logout if logged_in?
    omniauth_path = "/auth/#{params[:provider]}"
    omniauth_path << "?invitation_token=#{params[:invitation_token]}" if params[:invitation_token]
    redirect_to omniauth_path
  end

  # To create user when user login from linkedin and facebook
  def omniauth_create
#    if params[:user][:email]
    auth = request.env['omniauth.auth']
    email = request.env['omniauth.auth'].info.email
    @authentication = Authentication.find_or_create_with_omniauth(auth)
    if logged_in?
      if @authentication.user == current_user
        # User is signed in so they are trying to link an identity with their
        # account. But we found the identity and the user associated with it
        # is the current user. So the identity is already associated with
        # this user. So let's display an error message.
        redirect_to after_signup_path, notice: "#{current_user.name}, you are already logged in."
      else
        # The identity is not associated with the current_user so lets
        # associate the identity
        @authentication.user = current_user
        @authentication.save()
        redirect_to after_signup_path, notice: "Successfully linked #{@authentication.provider.titleize} account!"
      end
    else
      if @authentication.user.present?
        # The identity we found had a user associated with it so let's
        # just log them in here
        if @authentication.user.active?
          auto_login(@authentication.user)
        else
          redirect_to root_path, alert: "Your email is not verified yet. Please follow the link in the activation email sent to you." and return
        end
        if @authentication.user.is_registration_completed?
          redirect_to after_signup_path, notice: "Logged in from #{@authentication.provider.titleize}!"
        else
          redirect_to edit_profile_path('courses_studying'), notice: "Please complete your profile, before you proceed."
        end
      else
        # No user associated with the identity so we need to create a new one, chck
        @authentication.build_user_with_omniauth(nil, request.env['omniauth.params']['invitation_token'])
        if @authentication.has_valid_user_email? and @authentication.save(validate: false)
          after_create_with_omniauth
        else
          session['sorcery.omniauth'] = {uid: auth['uid'], provider: auth['provider'], invitation_token: request.env['omniauth.params']['invitation_token']}
          render 'omniauth_edit'
        end
      end
    end
  end

  # To create user.
  def create
    if auth = session['sorcery.omniauth']
      auth = auth.with_indifferent_access
      @authentication = Authentication.find_or_create_with_omniauth(auth, true)
      @authentication.build_user_with_omniauth(user_params[:email], auth[:invitation_token])
      @user = @authentication.user
      if @authentication.has_valid_user_email? and @authentication.save(validate: false)
        session.delete('sorcery.omniauth')
        after_create_with_omniauth
      else
        respond_to do |format|
          format.html {render 'omniauth_edit'}
          format.js { render template: 'users/omniauth_edit', object: @user, replace: '#omniauth-add-email'}
        end
      end
    else
      logout if logged_in?
      @user = User.new(user_params)
      if @user.type.blank?
        @user.type = 'Student'
      end
      if @user.save
        respond_to do |format|
          message = " An activation email will be sent momentarily to your email address provided. Please follow the link in the email in order to activate your profile. Please check your spam folder if you do not receive our email momentarily."
          UserMailer.delay(queue: :mailer).activation_needed_email(@user.id, true)
          format.html {redirect_to root_path, notice: message}
          format.js {redirect_via_turbolinks_to root_path, notice: message}
        end
      else
        respond_to do |format|
          format.html {render 'new'}
          format.js { render partial: 'form', object: @user, replace: 'form#new_user'}
        end
      end
    end
  end

  # To upgrade user from student to tutor
  def upgrade
    @user = current_user
    respond_to do |format|
      if @user.upgrade!
        if params[:upgrade_type] == 'tutor'
          format.html {redirect_to edit_profile_path('courses-tutoring')}
          format.js {redirect_via_turbolinks_to edit_profile_path('courses-tutoring')}
        else
          format.html {redirect_to edit_profile_path('courses_studying')}
          format.js {redirect_via_turbolinks_to edit_profile_path('courses_studying')}
        end
      else
        message = "Could not upgrade. Please try again."
        format.html {redirect_to dashboard_path, notice: message}
        format.js {redirect_via_turbolinks_to dashboard_path, notice: message}
      end
    end
  end

  # To activate user when user click on activation link in email
  def activate
    if (@user = User.load_from_activation_token(params[:id]))
      invite = Invite.where("invitee_id = ? AND registered = ?", @user.id, true).first
      if @user.activate!
        if invite.present?
          AcceptInviteWorker.perform_async(invite.id)
        end
      end
      UserMailer.delay(queue: :mailer).activation_success_email(@user.id, true)
      auto_login(@user)
      respond_to do |format|
        message = "Your account has been activated. Please complete your profile."
        redirect_path = Invoice.find_by_user_email(@user.email).present? ? invoices_path : after_signup_path
        format.html {redirect_to redirect_path, notice: message}
        format.js {redirect_via_turbolinks_to redirect_path, notice: message}
      end
    else
      not_authenticated
    end
  end

  # To upload user profile picture.
  def upload_image
    @user = current_user
    @user.update_attributes(user_params)
  end

  private
  def user_params
    params.required((current_user.try(:type) || 'User').downcase.to_sym).permit(
      :name, :last_name, :email, :password, :password_confirmation, :phone, :invitation_token, :type,
      profile_image_attributes: [:crop_x, :crop_y, :crop_w, :crop_h, :image, :id]
    )
  end

  def after_signup_path
    if session[:tutoring_session]
      profile_path(session[:tutoring_session][:tutor_id])
    else
      user = current_user || @user
      if user.student?
        personal_calendar_path
      else
        user.is_registration_completed? ? personal_calendar_path : edit_profile_path('courses-tutoring')
      end
    end
  end

  def after_create_with_omniauth
    if @authentication.user.email == @authentication.email
      auto_login(@authentication.user)
      unless @authentication.user.is_registration_completed?
        redirect_to edit_profile_path('courses_studying'), notice: "Please complete your profile, before you proceed."
      else
        redirect_to dashboard_url, notice: "Logged in from #{@authentication.provider.titleize}!"
      end
    else
      respond_to do |format|
        message = " An activation email will be sent momentarily to your email address provided. Please follow the link in the email in order to activate your profile. Please check your spam folder if you do not receive our email momentarily."
        UserMailer.delay(queue: :mailer).activation_needed_email(@user.id, true)
        format.html {redirect_to root_path, notice: message}
        format.js {redirect_via_turbolinks_to root_path, notice: message}
      end
    end
  end

end
