class UsersController < ApplicationController

  before_action :ensure_valid_user, except: [:login, :verify_login, :new, :create]

  def login

  end

  def logout
    set_current_user(nil)
    session.destroy
    flash[:notice] = "Logged out"
    redirect_to root_path
  end

  def verify_login
    if user = User.authenticate(params[:username], params[:password])
      set_current_user(user)
      flash[:notice] = "Welcome, #{user.display_name}"
      redirect_to root_path
    else
      flash[:error] = "Invalid credentials"
      render :login
    end
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)

    if @user.save
      set_current_user(@user)
      redirect_to root_path, notice: 'User was successfully created.'
    else
      render action: :new
    end
  end

  def edit
    @user = current_user
  end

  def update
    @user = current_user
    if @user.update(user_params)
      redirect_to root_path, notice: 'User account updated'
    else
      render action: 'edit'
    end
  end

  private

  def user_params
    params.require(:user).permit(:username, :email, :full_name, :password, :password_confirmation)
  end
end