class UsersController < ApplicationController

  def show_or_new
    response = env["omniauth.auth"] # dictionary with info about GitHub auth
    @email = response[:info][:email]
    @token = response[:credentials][:token]
    if user = User.find_by(email: @email) then
      user.token = @token # updating GitHub token
      user.save           # maybe we need external(non-model) check if the token is non-empty
      redirect_to user
    else
      @name = response[:info][:name]
      @nick = response[:info][:nickname]
      @avatar = response[:info][:image]
      @github = response[:info][:urls][:GitHub]
      render 'new'
    end
  end

  def create
    user = User.new do |us|
      us.name = params[:name]
      us.email = params[:email]
      us.token = params[:token]
      us.github = params[:github]
      us.nick = params[:nick]
      us.avatar = params[:avatar]
    end
    if user.save then
      redirect_to user
    else
      render 'new' # need to add flash with errors
    end
  end

  def show
    @user = User.find(params[:id])
    @public_repos = @user.public_repos
    @private_repos = @user.private_repos
  end

end
