package com.imofan.android.develop.sns;

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

import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/***
 * SSO登陆
 * @author poble
 *
 */
@SuppressLint("HandlerLeak")
public class MFSnsSSOLogin {
	private Context context;
	private int platform;
	private MFSnsAuthListener authListener;
	
	//腾讯sso登陆
	private Tencent mTencent;
	private static final String SCOPE = "get_user_info,get_simple_userinfo,get_user_profile,get_app_friends,"
	            + "add_share,add_topic,list_album,upload_pic,add_album,set_user_face,get_vip_info,get_vip_rich_info,get_intimate_friends_weibo,match_nick_tips_weibo";
	
	//新浪SSo登陆
	public WeiboAuth mWeibo;
	public SsoHandler mSsoHandler;
	
	/***
	 * sso登陆方法
	 * @param context 环境，必须是activity
	 * @param platform 登陆平台(腾讯微博、qq空间、新浪微博)
	 * @param authListener 登陆后回调接口
	 */
	public void SSOLogin(Context context,int platform,MFSnsAuthListener authListener){
		this.context = context;
		this.platform = platform;
		this.authListener = authListener;
		if(platform==MFSnsService.PLATFORM_QQ_WEIBO||platform==MFSnsService.PLATFORM_QQ_QZONE){
			tencentSSOLogin();
		}else if(platform==MFSnsService.PLATFORM_SINA_WEIBO){
			sinaSSOLogin();
		}
	}
	
	/***
	 * 腾讯sso登陆方法
	 */
	private void tencentSSOLogin(){
		mTencent = Tencent.createInstance(MFSnsConfig.CONSUMER_KEY_TECENT,context);
		mTencent.logout(context);
    	mTencent.login((Activity) context, SCOPE, new IUiListener() {
			
			@Override
			public void onError(UiError arg0) {
				if(null!=authListener&&null!=arg0){
					authListener.onFail(context, arg0.errorMessage);
				}
			}
			
			/*public void onComplete(JSONObject arg0) {
				new Thread(new GetUserInforTask(arg0.optString("access_token"),arg0.optString("expires_in"), arg0.optString("openid"))).start();
			}*/
			
			@Override
			public void onCancel() {
			}

			@Override
			public void onComplete(Object arg0) {
				JSONObject arg1;
				try {
					arg1 = new JSONObject(arg0.toString());
					new Thread(new GetUserInforTask(arg1.optString("access_token"),arg1.optString("expires_in"), arg1.optString("openid"))).start();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/***
	 * 注销qq
	 * @param context
	 */
	public void loginout(Context context){
		mTencent = Tencent.createInstance(MFSnsConfig.CONSUMER_KEY_TECENT,context);
		mTencent.logout((Activity) context);
	}
	
	/***
	 * 新浪sso登陆方法
	 */
	private void sinaSSOLogin(){
		//mWeibo = Weibo.getInstance(MFSnsConfig.CONSUMER_KEY_SINA, MFSnsConfig.CONSUMER_REDIRECT_URL_SINA);
		mWeibo = new WeiboAuth(context, MFSnsConfig.CONSUMER_KEY_SINA, MFSnsConfig.CONSUMER_REDIRECT_URL_SINA, "");
		mSsoHandler = new SsoHandler((Activity) context, mWeibo);
		mSsoHandler.authorize(new WeiboAuthListener() {
			
			@Override
			public void onWeiboException(WeiboException arg0) {
				if(null!=authListener&&null!=arg0){
					authListener.onFail(context, arg0.getMessage());
				}
			}
			
			@Override
			public void onComplete(Bundle arg0) {
				new Thread(new GetUserInforTask(arg0.getString("access_token"),arg0.getString("expires_in"), arg0.getString("uid"))).start();
			}
			
			@Override
			public void onCancel() {
				
			}
		});
	}
	
	/***
	 * 认证完成后，获取用户资料的线程
	 * 
	 * @author user
	 * 
	 */
	class GetUserInforTask implements Runnable {
		String access_token;
		String expires_in;
		String open_id;

		public GetUserInforTask(String access_token, String expires_in, String open_id) {
			this.access_token = access_token;
			this.expires_in = expires_in;
			this.open_id = open_id;
		}

		@Override
		public void run() {
			String result = "";
			if(platform==MFSnsService.PLATFORM_QQ_WEIBO||platform==MFSnsService.PLATFORM_QQ_QZONE){
				result = new TencentOauth(context).doResult(access_token, expires_in, open_id);
			}else if(platform==MFSnsService.PLATFORM_SINA_WEIBO){
				result = new SinaOauth(context).doResult(access_token, expires_in, open_id);
			}
			Message msg = new Message();
			msg.obj = result;
			doResultHandler.sendMessage(msg);
		}
	}
	
	/***
	 * 处理用户资料
	 */
	Handler doResultHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 登陆成功后，执行回调
			if (null != authListener) {
				authListener.onSucceeded(context, MFSnsUtil.getOpenUser(context, platform));
			}
			super.handleMessage(msg);
		}
	};
	
	/***
	 * sso登陆的activity需要重新该方法
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // sso 授权回调
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        if (mTencent != null){
        	mTencent.onActivityResult(requestCode, resultCode, data);
    	}
    }

}
