class UsersController < ApplicationController

  before_action :ensure_valid_user, except: [:show, :login, :verify_login, :new, :create]
  skip_before_action :verify_authenticity_token, only: [:verify_login]

  def show
    if current_user
      render json: UserSerializer.for(current_user)
    else
      render json: nil
    end
  end

  def login

  end

  def logout
    set_current_user(nil)
    session.destroy

    respond_to do |format|
      format.html { redirect_to root_path, notice: "Logged out" }
      format.json { render json: { success: true } }
    end
  end

  def verify_login

    respond_to do |format|
      if user = User.authenticate(params[:username], params[:password])
        set_current_user(user)
        format.html { redirect_to root_path, notice: "Welcome, #{user.display_name}" }
        format.json { render json: { success: true, user: UserSerializer.for(current_user).serialize } }
      else
        format.html { flash[:error] = "Invalid credentials"; render :login }
        format.json { render json: { success: false, message: 'Invalid Credentials', user: nil } }
      end
    end
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        set_current_user(@user)
        format.html { redirect_to root_path, notice: 'User created.' }
        format.json { render json: UserSerializer.for(@user), status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def edit
    @user = current_user
  end

  def update
    @user = current_user

    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to root_path, notice: 'User updated.' }
        format.json { render json: UserSerializer.for(@user) , status: :created, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  private

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