require "net/http"
require "uri"
require 'json'

class FacebookController< ApplicationController

	def register_fb
		user = User.find(params[:user])
		if !user.facebook
			user.build_facebook(fb_identifier: params[:identifier],connected: true)
			user.save!
		end
    	render :json=>{"success"=>true,"user"=>user.facebook.fb_identifier}.to_json
    	# respond_to do |format|
    	# 	format.js
    	# end
  	end

  	def get_friends
  		if current_user.facebook
	  		@url = "http://fb.tp.rulingcom.com/get_friends?identifier=" + current_user.facebook.fb_identifier
		    uri = URI.parse(@url)
		    http = Net::HTTP.new(uri.host, uri.port)
		    request = Net::HTTP::Get.new(uri.request_uri)
		    response = http.request(request)
		    friends = response.body
		    friends = JSON.parse(friends)
		    output = Array.new
		    friends.each do |friend|
		    	output << {"name"=>friend['name'],"identifier"=>friend['identifier']}
		    end
	  		render :json=>{"success"=>true,"count"=>friends.count,"friends"=>output}.to_json
	  	else
	  		render :json=>{"success"=>false,"message"=>"User is not connected to facebook."}.to_json
	  	end
  	end

  	def disconnect
  		user_fb = current_user.facebook
  		if user_fb
  			user_fb.destroy
  		end
  		render :json=>{"success"=>true}.to_json
  	end

end