package com.imofan.android.develop.sns.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;


import com.imofan.android.develop.sns.MFSnsAuthListener;
import com.imofan.android.develop.sns.MFSnsService;
import com.imofan.android.develop.sns.MFSnsUser;
import com.imofan.android.develop.sns.MFSnsUtil;
import com.imofan.android.develop.sns.OauthBuilder;
import com.imofan.android.develop.sns.RenRenOauth;
import com.imofan.android.develop.sns.SinaOauth;
import com.imofan.android.develop.sns.TencentOauth;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * 微博认证页面,采用oauth2.0认证协议进行认证
 * 
 * @author poble
 * 
 */
public class MFSnsOAuthActivity extends Activity {
    private String redirectUrl = ""; // 应用注册时，填写的回调url
    private String requestUrl = ""; // 请求页面，根据oauth2认证标志，添加各种参数
    private int platform;
    private WebView webview;
    private ProgressBar progressBar;
    private boolean tecentTag = true;// 解决，腾讯认证后，页面回调两次问题
    private static MFSnsAuthListener oauthListener;// 认证完成后，回调该监听器
    private CookieManager cookieManager = null;

    public static void setAuthListener(MFSnsAuthListener authListener) {
        oauthListener = authListener;
    }
    
    private OauthBuilder builder;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        initData();
        initView();
        initWebView();
    }
    /***
     * 初始化平台，创建builder
     */
    private void initData(){
        platform = this.getIntent().getIntExtra("platform", 0);
        switch (platform) {
        case MFSnsService.PLATFORM_SINA_WEIBO:
            builder = new SinaOauth(MFSnsOAuthActivity.this);
            break;
        case MFSnsService.PLATFORM_QQ_WEIBO:
            builder = new TencentOauth(MFSnsOAuthActivity.this);
            break;
        case MFSnsService.PLATFORM_QQ_QZONE:
            builder = new TencentOauth(MFSnsOAuthActivity.this);
            break;
        case MFSnsService.PLATFORM_RENREN:
            builder = new RenRenOauth(MFSnsOAuthActivity.this);
            //人人网时，将cookie功能禁掉
            CookieSyncManager.createInstance(this);   
            CookieManager cookieManager = CookieManager.getInstance();  
            cookieManager.setAcceptCookie(false);  
            break;
        default:
            toastMessage("没有配置该开放平台相关url即参数");
            break;
        }
        redirectUrl = builder.getRedirectUrl();
        requestUrl = builder.getRequestUrl();
    }
    /***
     * 初始化组件
     */
    private void initView(){
        // 初始化frameLayout
        FrameLayout contentLayout = new FrameLayout(this);
        FrameLayout.LayoutParams frameParam = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER);
        contentLayout.setLayoutParams(frameParam);
        // 初始化webView组件
        webview = new WebView(this);
        FrameLayout.LayoutParams webParam = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER);
        webview.setLayoutParams(webParam);
        // 初始化progressBar组件
        progressBar = new ProgressBar(this);
        FrameLayout.LayoutParams progressBarParam = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        progressBar.setLayoutParams(progressBarParam);
        // 将各个子组件加入layout中
        contentLayout.addView(webview);
        contentLayout.addView(progressBar);
        setContentView(contentLayout);
    }
    /***
     * 初始化webview
     */
    private void initWebView(){
        webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webview.loadUrl(url);
                //人人网时，将cookie功能解禁
                if(url.contains("http://graph.renren.com/oauth/authorize?")){
                    CookieManager cookieManager = CookieManager.getInstance();  
                    cookieManager.setAcceptCookie(true);
                }
               /*  */
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                if (url.startsWith(redirectUrl)) {
                    if(url.contains("access_token")){
                        webview.stopLoading();
                        URL u;
                        try {
                            u = new URL(url);
                            Bundle b = decodeUrl(u.getQuery());
                            b.putAll(decodeUrl(u.getRef()));
                            if (tecentTag) {
                                progressBar.setVisibility(View.VISIBLE);
                                new Thread(new MyRun(b.getString("access_token"), b.getString("expires_in"), b.getString("uid"))).start();
                                tecentTag = false;
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } 
                    }else{
                        MFSnsOAuthActivity.this.finish();
                    }
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                progressBar.setVisibility(View.GONE);
            }
        });
        webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsConfirm(WebView view, String url,
                    String message, JsResult result) {
                final JsResult result1 = result ;
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MFSnsOAuthActivity.this);
                alertBuilder.setTitle(message).setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                result1.confirm();
                            }
                        }
                ).setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                                result1.cancel();
                            }
                        }
                ).show();
                return true;
            }
        });
        Log.v("*******requestUrl", requestUrl);
        webview.loadUrl(requestUrl);
    }
    /**
     * 认证成功后，处理回调url中的参数
     * 
     * @param s
     * @return
     */
    private Bundle decodeUrl(String s) {
        Bundle params = new Bundle();
        if (s != null && !s.trim().equals("")) {
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");
                params.putString(URLDecoder.decode(v[0]),URLDecoder.decode(v[1]));
            }
        }
        return params;
    }

    /**
     * 用户提示toast
     * 
     * @param message
     */
    private void toastMessage(String message) {
        Toast.makeText(MFSnsOAuthActivity.this, message, Toast.LENGTH_LONG).show();
    }
    /***
     * 认证完成后，获取用户资料的线程
     * @author user
     *
     */
    class MyRun implements Runnable{
        String access_token;
        String expires_in;
        String open_id; 
        public MyRun(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 = "";
            result = builder.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 != oauthListener) {
                progressBar.setVisibility(View.VISIBLE);
                if(platform == MFSnsService.PLATFORM_SINA_WEIBO){
                    oauthListener.onSucceeded(MFSnsOAuthActivity.this, MFSnsUtil
                            .getOpenUser(MFSnsOAuthActivity.this, platform));
                }else if(platform == MFSnsService.PLATFORM_RENREN){
                    oauthListener.onSucceeded(MFSnsOAuthActivity.this, MFSnsUtil
                            .getOpenUser(MFSnsOAuthActivity.this, platform));
                }else{
                    MFSnsUser user = MFSnsUtil.getOpenUser(MFSnsOAuthActivity.this, MFSnsService.PLATFORM_QQ_QZONE);
                        if(user.getNickname()==null||user.getNickname().equals("")){
                            user = MFSnsUtil.getOpenUser(MFSnsOAuthActivity.this, MFSnsService.PLATFORM_QQ_WEIBO);
                        }
                    oauthListener.onSucceeded(MFSnsOAuthActivity.this, user);
                }
                
            }
            super.handleMessage(msg);
        }
    };

    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
