package com.imofan.android.develop.sns;

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 SinaOauth implements OauthBuilder {
    private String requestUrl = "";         //请求url
    private String redirectUrl = "";        //认证回调url
    private String clientId = "";           //app key
    private Context context;                //上下文环境
    
    private int platform = MFSnsService.PLATFORM_SINA_WEIBO;
    /***
     * 构造方法
     * @param context
     */
    public SinaOauth(Context context){
        
        this.clientId = MFSnsConfig.CONSUMER_KEY_SINA;
        this.redirectUrl = MFSnsConfig.CONSUMER_REDIRECT_URL_SINA;
        this.requestUrl = "https://api.weibo.com/oauth2/authorize?client_id=" + clientId + "&response_type=token&redirect_uri=" + redirectUrl + "&display=mobile&forcelogin=true&scope=all";
        this.context = context;
    }
    
    @Override
    public String doResult(String param1, String param2, String param3) {
        String result = "failed";
        String usermessage = "";
        JSONObject obj = null;
        usermessage = MFSnsUtil.getUserInfo(platform, param1,param3);
        
        try {
        	if(null!=usermessage){
        		obj = new JSONObject(usermessage);
        	}
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        if(obj!=null&&obj.optString("screen_name")!=null&&!obj.optString("screen_name").equals("")){
            //构造用户信息json
            JSONObject userObj = new JSONObject();
            try {
				userObj.put("access_token", param1);
				userObj.put("openid", param3);
				userObj.put("nickname", obj.optString("screen_name"));
				userObj.put("brief", obj.optString("description"));
				userObj.put("icon_50", obj.optString("profile_image_url"));
				userObj.put("icon_180", obj.optString("profile_image_url").replace("/50/", "/180/"));
				userObj.put("expires_in", param2);
				userObj.put("login_time", System.currentTimeMillis());
				result = userObj.toString();
			} catch (JSONException e) {
				result = "";
				e.printStackTrace();
			}
            //保存用户信息
            SharedPreferences sharedPreferences = context.getSharedPreferences(
                "platforms", Context.MODE_PRIVATE);
            Editor editor = sharedPreferences.edit();// 获取编辑器
            editor.putString("platform" + MFSnsService.PLATFORM_SINA_WEIBO, result);
            editor.commit();// 提交修改
        }
        return result;
    }

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

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

}
