class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def twitter
    auth = request.env["omniauth.auth"]
    @user = User.find_or_initialize_by tw_uid: auth['uid']
    @user.attributes = {
      tw_nick: auth['info']['nickname'],
      tw_name: auth['info']['name'],
      tw_img_url: auth['info']['image'],
      tw_updated_at: Time.now,
    }
    @user.lang ||= auth['extra']['raw_info']['lang']
    @user.name ||= auth['info']['name']
    @user.timezone ||= auth['extra']['raw_info']['time_zone']
    @user.new_record? && User.count == 0 and @user.is_admin = true
    @user.save

    if @user.errors.empty?
      sign_in_and_redirect @user, event: :authentication
      set_flash_message(:notice, :success, kind: "Twitter") if is_navigational_format?
    else
      redirect_to new_user_session_path
    end
  end
end
