class PasswordsController < ApplicationController
  skip_before_filter :require_login

  # To request for changing the password. It find the user by email provided and sends emails with instructions for changing password.
  def create
    if @user = User.find_by(email: params[:password][:email])
      @user.deliver_reset_password_instructions!
      respond_to do |format|
        @message = 'Instructions have been sent to your email address. Please check your inbox and spam folder.'
        UserMailer.delay(queue: :mailer).reset_password_email(@user.id)
        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  {}
      end
    end
  end

  # Opens form for reset password request.
  def new
    render layout: false
  end

  # Find the user with valid reset password token to change the password.
  def edit
    @user = User.load_from_reset_password_token(params[:id])
    @token = params[:id]
    not_authenticated if !@user
  end

  # Update method to reset the password. It saves the newly created password by the user.
  def update
    @token = params[:token]
    @user = User.load_from_reset_password_token(@token)
    not_authenticated if !@user

    @user.password = params[@user.type.downcase.to_sym][:password]
    @user.password_confirmation = params[@user.type.downcase.to_sym][:password_confirmation]
    @user.valid?

    if @user.errors[:password].empty?
      @user.save(validate: false)
      redirect_to(root_path, :notice => 'Password was successfully updated.')
    else
      render 'edit'
    end
  end

end
