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

import java.io.File;
import java.util.ArrayList;

import com.imofan.android.develop.sns.MFSnsAuthListener;
import com.imofan.android.develop.sns.MFSnsConfig;
import com.imofan.android.develop.sns.MFSnsSSOLogin;
import com.imofan.android.develop.sns.MFSnsService;
import com.imofan.android.develop.sns.MFSnsShareContent;
import com.imofan.android.develop.sns.MFSnsShareListener;
import com.imofan.android.develop.sns.MFSnsUser;
import com.imofan.android.develop.sns.MFSnsUtil;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

/***
 * 分享选择页面
 * @author poble
 *
 */
public class MFSnsSelectPlatformActivity extends Activity{
	private static MFSnsShareListener shareListener = null;
	private MFSnsShareContent contentMessage = null;
	private boolean isHttpImage = false;
	private boolean imageDownDone = false;
	
	private LinearLayout topLayout;			//顶部布局 
	private Button QQWeiBoBtn;				//腾讯微博
	private Button webChatFriendsBtn;		//朋友圈
	private Button webChatBtn;				//微信
	private Button sinaBtn;					//新浪微博
	private Button QzoneBtn;				//QQ空间
	private Button cancleBtn;				//取消
	
	private IWXAPI api = null;
	private Tencent mTencent;
	private MFSnsSSOLogin ssoLogin;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		contentMessage = (MFSnsShareContent) this.getIntent().getSerializableExtra("content");
		setContentView(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this,"layout", "imofan_weibo_select_platform_activity"));
		initView();
		api = WXAPIFactory.createWXAPI(MFSnsSelectPlatformActivity.this, MFSnsConfig.CONSUMER_WEIXIN_APPID, true);
	    api.registerApp(MFSnsConfig.CONSUMER_WEIXIN_APPID);
	    mTencent = Tencent.createInstance(MFSnsConfig.CONSUMER_KEY_TECENT, getApplicationContext());
	}
	
	/***
	 * 初始化view
	 */
	private void initView(){
		topLayout =  (LinearLayout) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_top_layout"));
		QQWeiBoBtn = (Button) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_share_qq_weibo"));
		webChatFriendsBtn = (Button) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_share_webchat"));
		webChatBtn = (Button) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_share_qqfriends"));
		sinaBtn = (Button) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_share_sina"));
		QzoneBtn = (Button) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_share_qzone"));
		cancleBtn = (Button) findViewById(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "id","imofan_share_cancle"));
		
		 if(null==contentMessage.getImage()||contentMessage.getImage().equals("")){
	     }else{
	    	 setImage(contentMessage.getImage());
	     }
		topLayout.setOnClickListener(clickListener);
		QQWeiBoBtn.setOnClickListener(clickListener);
		webChatFriendsBtn.setOnClickListener(clickListener);
		webChatBtn.setOnClickListener(clickListener);
		sinaBtn.setOnClickListener(clickListener);
		QzoneBtn.setOnClickListener(clickListener);
		cancleBtn.setOnClickListener(clickListener);
	}
	
	private OnClickListener clickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			int id = v.getId();
			if(id == topLayout.getId()){
				back();
			}else if(id == QQWeiBoBtn.getId()){
				shareToWeibo(MFSnsService.PLATFORM_QQ_WEIBO);
			}else if(id == webChatFriendsBtn.getId()){
				WeiXinClick(SendMessageToWX.Req.WXSceneTimeline);//微信朋友圈
			}else if(id == webChatBtn.getId()){
				WeiXinClick(SendMessageToWX.Req.WXSceneSession);//微信
			}else if(id == sinaBtn.getId()){
				shareToWeibo(MFSnsService.PLATFORM_SINA_WEIBO);
			}else if(id == QzoneBtn.getId()){
				shareToQzone();
			}else if(id == cancleBtn.getId()){
				back();
			}
			
		}
	};
	
	/***
	 * 向微博分享
	 * @param platform
	 */
	private void shareToWeibo(int platform){
		if(MFSnsUtil.isAuthorized(MFSnsSelectPlatformActivity.this, platform)){
			Intent intent = new Intent(this, MFSnsUploadActivity.class);
		    intent.putExtra("content", contentMessage);
		    intent.putExtra("platform", platform);
		    MFSnsUploadActivity.setShareListener(shareListener);
		    startActivity(intent);
		    overridePendingTransition(MFSnsConfig.getIdByReflection(this, "anim", "bottom_fade_in"), MFSnsConfig.getIdByReflection(this, "anim", "imofan_current_out"));
		    
		    new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					finish();
				}
			}, 500);
		}else{
			 final int platf = platform;
	            final MFSnsShareContent cont = contentMessage;
	            final MFSnsShareListener listener = shareListener;
	            MFSnsAuthListener authListener = new MFSnsAuthListener() {
	                @Override
	                public void onSucceeded(Context context, MFSnsUser openUser) {
	                    ((Activity) context).finish();
	                    // 去分享确认页面
	                    Intent intent = new Intent(context,MFSnsUploadActivity.class);
	                    intent.putExtra("platform", platf);
	                    intent.putExtra("content", cont);
	                    MFSnsUploadActivity.setShareListener(listener);
	                    context.startActivity(intent);
	                    overridePendingTransition(MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "anim", "bottom_fade_in"), MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "anim", "imofan_current_out"));
	                }
	                @Override
	                public void onFail(Context context, String errMessage) {
	                	
	                }
	            };
	            ssoLogin = new MFSnsSSOLogin();
	            ssoLogin.SSOLogin(MFSnsSelectPlatformActivity.this, platform, authListener);
		}
	}
	
	public static void setShareListener(MFSnsShareListener shareListener) {
		MFSnsSelectPlatformActivity.shareListener = shareListener;
    }
	
	@Override
	protected void onResume() {
		super.onResume();
		new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            	topLayout.setBackgroundColor(Color.parseColor("#b0222222"));
            }
        },500);
		if(shareListener!=null){
			shareListener.onSelectedResume(this);
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if(shareListener!=null){
			shareListener.onSelectedPause(this);
		}
	}
	
	/***
	 * 向qq空间分享
	 */
	private void shareToQzone () {
			final Bundle params = new Bundle();
			//分享类型
			params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
		    params.putString(QzoneShare.SHARE_TO_QQ_TITLE, contentMessage.getTitle());//必填
		    //params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, contentMessage.getDescription());//选填
		    params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, contentMessage.getUrl());//必填
		    if(null!=contentMessage.getImage()&&!contentMessage.getImage().equals("")){
		    	 ArrayList<String> list = new ArrayList<String>();
				 list.add(contentMessage.getImage());
				 params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,list);
		    }else{
		    	params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
		    }
		    if(shareListener!=null){
		    	shareListener.onTencentQzoneSucceeded(this);
		    }
		    mTencent.shareToQzone(MFSnsSelectPlatformActivity.this, params, new IUiListener() {

                @Override
                public void onCancel() {
                	
                }

                @Override
                public void onError(UiError e) {
                }

				@Override
				public void onComplete(Object response) {
					
				}

            });
		}
	
	/***
	 * 向微信分享
	 * @param type
	 */
	private void WeiXinClick(int type){

   	 if (isHttpImage) { // 是网络图片，判断网络图片是否下载完成
            if (!imageDownDone) {
                showToast("图片尚未下载完成，请稍等");
                return;
            }
        }
        File imageFile = null;
        if(null!=contentMessage.getImage()){
            if (isHttpImage) {
                imageFile = new File(getCachUrl());
            } else {
                imageFile = new File(contentMessage.getImage());
            }  
        }
       
        final WXWebpageObject appdata = new WXWebpageObject();
        appdata.webpageUrl = contentMessage.getWapUrl();
       
       
        final WXMediaMessage msg = new WXMediaMessage();
        if(null!=imageFile){
       	 	Bitmap tmp = BitmapFactory.decodeFile(imageFile.getPath());
            msg.setThumbImage(ThumbnailUtils.extractThumbnail(tmp, 150, 150));
        }
        msg.title = contentMessage.getTitle();
        if(null!=contentMessage.getDescription()){
            msg.description = contentMessage.getDescription();
        }
        msg.mediaObject = appdata;
        
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = type;
        api.sendReq(req);
        if(type == SendMessageToWX.Req.WXSceneTimeline){
       	 if(null!=shareListener){
                shareListener.onWeiXinFriendsSucceeded(MFSnsSelectPlatformActivity.this);
            }
        }else if(type == SendMessageToWX.Req.WXSceneSession){
       	 if(null!=shareListener){
                shareListener.onWeiXinSucceeded(MFSnsSelectPlatformActivity.this);
            }
        }
   }
	
	/***
	 * 返回
	 */
	private void back(){
        topLayout.setBackgroundColor(Color.parseColor("#00222222"));
        MFSnsSelectPlatformActivity.this.finish();
        MFSnsSelectPlatformActivity.this.overridePendingTransition(0, MFSnsConfig.getIdByReflection(MFSnsSelectPlatformActivity.this, "anim","bottom_fade_out"));
	}
	
	@Override
	public void onBackPressed() {
		back();
	}
	
	private void setImage(String url) {
        if (url.startsWith("http")) {
            isHttpImage = true;
            if (getCach(url)) {
                imageDownDone = true;
            } else {
                DownloadTask task = new DownloadTask();
                task.execute(url);
                return;
            }

        } else {
        	imageDownDone = true;
        }
    }
	
	 private boolean getCach(String key) {
	        SharedPreferences sharedPreferences = getSharedPreferences("uploadImage", Context.MODE_PRIVATE);
	        String url = sharedPreferences.getString("imageUrl", "");
	        if (key.equals(url)) {
	            return true;
	        } else {
	            return false;
	        }
	}

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            File file = MFSnsUtil.saveImage(MFSnsSelectPlatformActivity.this,params[0]);
            setCach(params[0]);
            return file.getAbsolutePath();
        }

        @Override
        protected void onPostExecute(String result) {
        	super.onPostExecute(result);
        	if(null!=result&&!result.equals("")){
        		imageDownDone = true;
        	}
        }
    }
    
    private void setCach(String key) {
        SharedPreferences sharedPreferences = getSharedPreferences(
                "uploadImage", Context.MODE_PRIVATE);
        Editor editor = sharedPreferences.edit();// 获取编辑器
        editor.putString("imageUrl", key);
        editor.commit();// 提交修改
    }
    
    private String getCachUrl() {
        String path = MFSnsSelectPlatformActivity.this.getDir("cacheImg", Activity.MODE_PRIVATE).getAbsolutePath().toString()+"/shareImg.cache";
        return path;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	if(null!=ssoLogin){
    		ssoLogin.onActivityResult(requestCode, resultCode, data);
    	}
    }
    
    private void showToast(String message){
        Toast.makeText(MFSnsSelectPlatformActivity.this, message,Toast.LENGTH_SHORT).show();
    }
}
