class SessionsController < ApplicationController
  def new
  end

  # GET /log_in
  def create
    if params[:username].nil? || params[:dialect].nil?
      redirect_to root_url and return
    end

    user = User.find_or_create_by(username: params[:username])

    begin
      ChatRoom.default_chat_room.add_user(user, params[:dialect])
      session[:user_id] = user.id
      flash[:info] = "Welcome to the Chat #{user.username} ;) Tip: point your mouse cursor over the text to see the original message!"
      redirect_to chatroom_path and return
    rescue ArgumentError
      redirect_to root_url and return
    rescue UserAlreadyInChatRoomError
      flash[:danger] = "This username is already in use"
      render 'new' and return
    end
  end

  # GET /log_out
  def destroy
    user_id = session[:user_id]
    unless user_id.nil?
      user = User.find(user_id)
      session[:user_id] = nil
      ChatRoom.default_chat_room.remove_user(user_id, user.username)
      redirect_to root_url, :notice => "Logged out!" and return
    else
      redirect_to root_url
    end
  end


end
