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

import java.io.File;

import com.imofan.android.develop.sns.MFSnsConfig;
import com.imofan.android.develop.sns.MFSnsHttpUtil;
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 android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/***
 * 分享确定页面
 * 
 * @author poble
 * 
 */

public class MFSnsUploadActivity extends Activity {
   
    private MFSnsShareContent contentMessage;
    private int platform;
    private static MFSnsShareListener shareListener;
    private EditText contentEditText = null;
    private TextView countTextView = null;
    private ProgressBar weiboShareProgressBar = null;
    private boolean isHttpImage = false;
    private boolean imageDownDone = false;
    private TextView submit;
    private TextView tittleView;
    private ImageView shareImage;
    private LinearLayout topLayout;
    private FrameLayout cancleLayout;
    private int contentlength = 140;        //文本框可以输入的文字长度
    private String shareResult;
    
    public static void setShareListener(MFSnsShareListener shareListener) {
        MFSnsUploadActivity.shareListener = shareListener;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this,"layout", "imofan_weibo_share_activity"));
        initView();
    }

    /**
     * 用于初始化view和事件监听
     */
    private void initView() {
        // 获取Intent中传递信息
        contentMessage = (MFSnsShareContent) this.getIntent().getSerializableExtra("content");
        platform = this.getIntent().getIntExtra("platform",-1);
        if(null!=contentMessage&&null!=contentMessage.getQqWeiboHideContent()&&!contentMessage.getQqWeiboHideContent().equals("")){//计算文本可以输入的字符个数
            contentlength = contentlength - MFSnsUtil.lengthOfQuanJiao(contentMessage.getQqWeiboHideContent());
        }else{
            contentlength = contentlength - MFSnsUtil.lengthOfQuanJiao(contentMessage.getHideContent());
        }
        

        // 初始化组件信息
        tittleView = (TextView) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id", "imofan_title"));
        if(platform==MFSnsService.PLATFORM_QQ_WEIBO){
        	tittleView.setText("腾讯微博");
        }else{
        	tittleView.setText("新浪微博");
        }
        topLayout = (LinearLayout) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id","imofan_top_trans_layout"));
        submit = (TextView) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id","imofan_weibo_share_activity_submit"));
        cancleLayout = (FrameLayout) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id","imofan_back_layout"));
        shareImage = (ImageView) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id", "imofan_share_image"));
        contentEditText = (EditText) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id","imofan_weibo_share_activity_content"));
        weiboShareProgressBar = (ProgressBar) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id","imofan_weibo_share_refresh_loadprogress"));
        contentEditText.setText(contentMessage.getContent());
        if (contentMessage.getImage() != null&& !"".equals(contentMessage.getImage())) {
           setImage(contentMessage.getImage());
        }
        countTextView = (TextView) findViewById(MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id", "imofan_weibo_share_count"));
        int textLength = contentEditText.getText().toString().length();
        if(contentlength-textLength<=0){
            countTextView.setText("已超过" + (textLength - contentlength) + "字");
            countTextView.setTextColor(Color.parseColor("#CF1111"));
        }else{
            countTextView.setText("还可以输入" + (contentlength - contentEditText.getText().toString().length()) + "字");
            countTextView.setTextColor(Color.parseColor("#B3B3B3"));
        }
     
        //输入框控制
        contentEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = contentEditText.getText().toString().length();
                if(length>contentlength){
                    countTextView.setText("已超过"+ (length - contentlength) + "字");
                    countTextView.setTextColor(Color.parseColor("#CF1111"));
                }else{
                    countTextView.setText("还可以输入"+ (contentlength - length) + "字");
                    countTextView.setTextColor(Color.parseColor("#B3B3B3"));
                }
                
            }
        });
        // 设置发布按钮监听事件
        submit.setOnClickListener(listener);
        topLayout.setOnClickListener(listener);
        cancleLayout.setOnClickListener(listener);
    }
    OnClickListener listener = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            int viewId = v.getId();
            if(viewId == MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "id", "imofan_weibo_share_activity_submit")){
                submit();//发表
            }else if(viewId == cancleLayout.getId()){
            	back();
            }else if(viewId == topLayout.getId()){
            	back();
            }
        }
    };  
    /***
     * 提交
     */
    private void submit(){
        //提交
        if (MFSnsHttpUtil.isNetworkAvailable(MFSnsUploadActivity.this)) {
            if (isHttpImage) { // 是网络图片，判断网络图片是否下载完成
                if (!imageDownDone) {
                    showToast("图片尚未下载完成，请稍等");
                    return;
                }
            }
            if (null == contentEditText.getText().toString() || "".equals(contentEditText.getText().toString().trim())) {
                showToast("内容不能为空");
                return;
            }
            if (null == contentEditText.getText().toString() || contentEditText.getText().toString().trim().length()>contentlength) {
                showToast("字数超过限制");
                return;
            }
            weiboShareProgressBar.setVisibility(View.VISIBLE);
            submit.setEnabled(false);
            sendThread.start();
        } else {
            showToast("没有找到可用网络");
        }
    
    }
    /**
     * 处理请求结果的handler
     */
    private Handler doresult = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 成功，回调成功方法，失败，回调失败方法
            weiboShareProgressBar.setVisibility(View.GONE);
            submit.setEnabled(true);
            if (null != shareListener) {
                if(shareResult.equals("mf_share_success")){
                	 if(platform == MFSnsService.PLATFORM_SINA_WEIBO){  //新浪微博
                		 shareListener.onSinaSucceeded(MFSnsUploadActivity.this);
                	 }else{
                		 shareListener.onTencentWeiBoSucceeded(MFSnsUploadActivity.this);
                	 }
                }
            }
            String share_result = "";
            if(share_result.equals("")){
                share_result = "分享成功";
            }else{
                share_result += "分享失败";
            }
            showToast(share_result);
            back();
        }
    };
    /**
     * 向服务器发送http请求的线程
     */
    private Thread sendThread = new Thread(new Runnable() {

        @Override
        public void run() {
            if(platform == MFSnsService.PLATFORM_QQ_WEIBO){
            	shareResult = sendToPlatform(MFSnsService.PLATFORM_QQ_WEIBO);
            }else if(platform == MFSnsService.PLATFORM_SINA_WEIBO){
            	shareResult = sendToPlatform(MFSnsService.PLATFORM_SINA_WEIBO);
            }
            Message msg = new Message();
            msg.obj = "shareResult";
            doresult.sendMessage(msg);
        }
    });
    
    private String sendToPlatform(int platform){
    	 // 根据平台信息，获取认证后的信息
        MFSnsUser user = MFSnsUtil.getOpenUser(MFSnsUploadActivity.this, platform);
        String result = null;
        
        String eidtTextString = null == contentEditText.getText()?"":contentEditText.getText().toString();
        String hideMessage = null == contentMessage.getHideContent()?"":contentMessage.getHideContent().toString();
        String imageUrl = null == contentMessage.getImage()?"":contentMessage.getImage().toString();
        String tittle = null ==contentMessage.getTitle()?"":contentMessage.getTitle().toString();
        String tittleUrl = null ==contentMessage.getUrl()?"":contentMessage.getUrl().toString();

       if(platform == MFSnsService.PLATFORM_SINA_WEIBO){  //新浪微博
            // 发送分享信息
            if (null == contentMessage.getImage()
                    || "".equals(contentMessage.getImage())) {
                result = MFSnsUtil.upload(platform, eidtTextString+hideMessage, user.getAccessToken(), user.getOpenId());
            } else {
                File imageFile = null;
                if (isHttpImage) {
                    imageFile = new File(getCachUrl());
                } else {
                    imageFile = new File(contentMessage.getImage());
                }
                result = MFSnsUtil.uploadWithPic(platform, eidtTextString+hideMessage, user.getAccessToken(), user.getOpenId(), imageFile);
            }
        } else if(platform == MFSnsService.PLATFORM_QQ_WEIBO){  //腾讯微博
            // 发送分享信息
            if (null == contentMessage.getImage()
                    || "".equals(contentMessage.getImage())) {
                result = MFSnsUtil.upload(platform, eidtTextString+hideMessage, user.getAccessToken(), user.getOpenId());
            } else {
                File imageFile = null;
                if (isHttpImage) {
                    imageFile = new File(getCachUrl());
                } else {
                    imageFile = new File(contentMessage.getImage());
                }
                result = MFSnsUtil.uploadWithPic(platform, eidtTextString+hideMessage, user.getAccessToken(), user.getOpenId(), imageFile);
            }
        }
        return result;
    }
    private void setImage(String url) {
        if (url.startsWith("http")) {
            isHttpImage = true;
            if (getCach(url)) {
                imageDownDone = true;
                viewSetImage(getCachUrl(), shareImage);
            } else {
                DownloadTask task = new DownloadTask();
                task.execute(url);
                return;
            }

        } else {
        	imageDownDone = true;
        	viewSetImage(url, shareImage);
        }
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            File file = MFSnsUtil.saveImage(MFSnsUploadActivity.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;
                viewSetImage(result, shareImage);
        	}
        }
    }

  
    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 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 = MFSnsUploadActivity.this.getDir("cacheImg", Activity.MODE_PRIVATE).getAbsolutePath().toString()+"/shareImg.cache";
        return path;
    }
    
    private void viewSetImage(String filePath,ImageView view){
    	BitmapFactory.Options options = new BitmapFactory.Options();   
		//设置工厂以240的密度来读取图片文件
        options.inDensity = 240;
        BitmapDrawable image = new BitmapDrawable(BitmapFactory.decodeFile(filePath,options));
        //设置图片在手机中以手机本身的密度来显示图片
        image.setTargetDensity(MFSnsUploadActivity.this.getApplicationContext().getResources().getDisplayMetrics());
	    view.setImageDrawable(image);
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            	topLayout.setBackgroundColor(Color.parseColor("#b0222222"));
            }
        },100);
        if(shareListener!=null){
        	shareListener.onResume(this);
        }
    }
    
    @Override
    protected void onPause() {
    	super.onPause();
    	if(shareListener!=null){
        	shareListener.onPause(this);
        }
    }
    /***
     * toastMessage
     * @param message
     */
    private void showToast(String message){
        Toast.makeText(MFSnsUploadActivity.this, message,Toast.LENGTH_SHORT).show();
    }
    
	/***
	 * 返回
	 */
	private void back(){
        topLayout.setBackgroundColor(Color.parseColor("#00222222"));
        MFSnsUploadActivity.this.finish();
        MFSnsUploadActivity.this.overridePendingTransition(0, MFSnsConfig.getIdByReflection(MFSnsUploadActivity.this, "anim","bottom_fade_out"));
	}
	
	@Override
	public void onBackPressed() {
		back();
	}
}
