package com.imofan.android.develop.sns;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/***
 * 人人网，认证builder
 * @author poble
 *
 */
public class RenRenOauth implements OauthBuilder {
    private String requestUrl = "";         //请求url
    private String redirectUrl = "";        //认证回调url
    private String clientId = "";           //app key
    private Context context;                //上下文环境
    /***
     * 构造方法
     * @param context
     */
    public RenRenOauth(Context context){
        this.context = context;
        this.clientId = MFSnsConfig.CONSUMER_KEY_RENREN;
        this.redirectUrl = MFSnsConfig.CONSUMER_REDIRECT_URL_RENREN;
        this.requestUrl = "https://graph.renren.com/oauth/authorize?client_id="+clientId+"&redirect_uri="+redirectUrl+"&response_type=token&scope=publish_feed";
    }
    @Override
    public String doResult(String param1, String param2, String param3){
        String result = "failed";
        JSONObject obj = null;
        String openId = null;
        try {
            //获取用户id
            openId = MFSnsUtil.postUserId(param1);
            //获取用户信息
            String usermessage = MFSnsUtil.getRenRenUserMessage(param1, openId);
            JSONArray array = new JSONArray(usermessage);
            obj = array.optJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(obj!=null&&obj.optString("name")!=null&&!obj.optString("name").equals("")){
            //构造用户json信息
            result = "{'access_token':'" + param1 + "','openid':'"
            + openId + "','nickname':'" + obj.optString("name")
            + "','brief':'" + obj.optString("birthday")
            + "','icon_50':'" + obj.optString("tinyurl")
            + "','icon_180':'" + obj.optString("mainurl")
            + "','expires_in':'" + param2 + "','login_time':'"
            + System.currentTimeMillis() + "'}";
            //保存用户信息
            SharedPreferences sharedPreferences = context.getSharedPreferences(
                    "platforms", Context.MODE_PRIVATE);
            Editor editor = sharedPreferences.edit();// 获取编辑器
            editor.putString("platform" + MFSnsService.PLATFORM_RENREN, result);
            editor.commit();// 提交修改
        }
        return result;
    }

    @Override
    public String getRequestUrl() {
        return requestUrl;
    }

    @Override
    public String getRedirectUrl() {
        return redirectUrl;
    }

}
