package org.mamute.auth;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

import com.google.common.base.Optional;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class FacebookAPI implements SocialAPI{
	
	private final Token accessToken;
	private final OAuthService service;
	
	public FacebookAPI(OAuthService service, Token accessToken) {
		this.service = service;
		this.accessToken = accessToken;
	}

	public Optional<SignupInfo> getSignupInfo() {
		String url = "https://graph.facebook.com/me?fields=name,email,location,username,id";
		Response response = makeRequest(url);
		JsonObject jsonObject = new JsonParser().parse(response.getBody()).getAsJsonObject();
		return SignupInfo.fromFacebook(jsonObject);
	}

	public String getUserId() {
		String url = "https://graph.facebook.com/me?fields=id";
		Response response = makeRequest(url);
		String body = response.getBody();
		if (response.getCode() != 200) {
			throw new IllegalArgumentException("http error: " + response.getCode() + ", facebook response body: " + body);
		}
		JsonObject jsonObj = new JsonParser().parse(body).getAsJsonObject();
		JsonElement jsonElement = jsonObj.get("id");
		if (jsonElement == null) {
			throw new IllegalArgumentException("facebook did not sent data requested! response body: " + body);
		}
		return jsonElement.getAsString();
	}

	private Response makeRequest(String url) {
		OAuthRequest request = new OAuthRequest(Verb.GET, url);
		service.signRequest(accessToken, request);
		Response response = request.send();
		return response;
	}

	@Override
	public Token getAccessToken() {
		return accessToken;
	}
}

@@ -385,18 +385,17 @@
 ialAPI%7B%0A
-%09
 %0A
+
 %09private
@@ -461,10 +461,9 @@
 ce;%0A
-%09
 %0A
+
 %09pub
@@ -709,17 +709,8 @@
 ion,
-username,
 id%22;
@@ -1055,161 +1055,8 @@
 ();%0A
-%09%09if (response.getCode() != 200) %7B%0A%09%09%09throw new IllegalArgumentException(%22http error: %22 + response.getCode() + %22, facebook response body: %22 + body);%0A%09%09%7D%0A
 %09%09Js
@@ -1492,16 +1492,16 @@
 quest);%0A
-
 %09%09Respon
@@ -1526,24 +1526,217 @@
 est.send();%0A
+%09%09String body = response.getBody();%0A%09%09if (response.getCode() / 100 != 2) %7B%0A%09%09%09throw new IllegalArgumentException(%22http error: %22 + response.getCode() + %22, facebook response body: %22 + body);%0A%09%09%7D%0A
 %09%09return res

Removing fb username and raising exception in case facebook response is != 2xx