class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def facebook
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.find_for_oauth(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def withings
    @user_vendor = current_user.vendors.where(:type => :withings)
    session["devise.withings_data"] = request.env["omniauth.auth"]

    if @user_vendor.nil?
      current_user.vendors.create(:type => :withings, uid: auth.uid, provider: auth.provider)
      set_flash_message(:notice, :success, :kind => "Nest") if is_navigational_format?
    end
  end

  def nest
    @user_vendor = current_user.vendors.where(:vendor_type => :nest).first
    session["devise.nest_data"] = request.env["omniauth.auth"]
    auth = request.env["omniauth.auth"]

    if @user_vendor.nil?
      current_user.vendors.create({
        vendor_type: :nest, 
        uid: auth.uid, 
        provider: auth.provider, 
        token: auth.token,
      })
      set_flash_message(:notice, :success, :kind => "Nest") if is_navigational_format?
    else
      @user_vendor.token = auth.token
      @user_vendor.save
    end
    redirect_to desktop_url
  end

  def twitter
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.find_for_oauth(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "twitter") if is_navigational_format?
    else
      session["devise.twitter_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end


  def after_sign_in_path_for(resource)
    if resource.email_verified?
      super resource
    else
      finish_signup_path(resource)
    end
  end
end