
package com.lianxin.pubqq.chat;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.chat.BaseActivity;
import com.lianxin.pubqq.chat.task.LoadLocalBigImgTask;
import com.lianxin.panqq.chat.utils.ImageCache;
import com.lianxin.panqq.client.callback.msgCallBack;
import com.lianxin.pubqq.chat.photoview.PhotoView;
import com.lianxin.panqq.main.EMChatManager;
import com.lianxin.panqq.main.EMSendManager;
import com.lianxin.panqq.main.PathUtil;
import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.chat.entity.ImageMessageBody;
import com.lianxin.panqq.chat.utils.ImageUtils;

/**
 * 下载显示大图
 * 
 */
public class ShowBigImageActivity extends BaseActivity {

	private ProgressDialog pd;
	private PhotoView image;
	private int default_res = R.drawable.default_avatar;
	private String localFilePath;
//	private String username;
	private Bitmap bitmap;
	private boolean isDownloaded;
	private ProgressBar loadLocalPb;
	Uri uri1;
	private int sendid = 10001;	
	private int msgid = 10001;
	private int chatType = EMMessage.ChatType.ChatType_USER;	
	private  EMMessage emMessage;		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_show_big_image);
		super.onCreate(savedInstanceState);
		
		image = (PhotoView) findViewById(R.id.image);
		loadLocalPb = (ProgressBar) findViewById(R.id.pb_load_local);

		default_res = getIntent().getIntExtra("default_image", R.drawable.default_avatar);

		Uri uri = getIntent().getParcelableExtra("uri");
		uri1 = getIntent().getParcelableExtra("uri1");		
		String remotepath = getIntent().getExtras().getString("remotepath");
		String secret=getIntent().getExtras().getString("secret");
		sendid = getIntent().getIntExtra("sendid",10002);
		msgid = getIntent().getIntExtra("message", 1);
		chatType = getIntent().getIntExtra("chattype", 1);		

		if (uri != null && new File(uri.getPath()).exists()) {
			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);
			int screenWidth = metrics.widthPixels;
			int screenHeight =metrics.heightPixels;
			bitmap = ImageCache.getInstance().get(uri.getPath());
			if (bitmap == null||bitmap != null) {

				LoadLocalBigImgTask task = new LoadLocalBigImgTask(this, uri.getPath(), image, loadLocalPb, screenWidth,
						screenHeight);				
				if (android.os.Build.VERSION.SDK_INT > 10) {
					task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
				} else {
					task.execute();
				}
			} else {
				image.setImageBitmap(bitmap);
			}
		} else if (remotepath != null) {
			System.err.println("download remote image");
			Map<String,String> maps=new HashMap<String,String>();
			//maps.put("Authorization", "Bearer "+EMChatConfig.getInstance().AccessToken());
			maps.put("Authorization", "Bearer "+EMChatManager.getInstance().getAccessToken());
			if(!TextUtils.isEmpty(secret))
			{
				maps.put("share-secret", secret);
			}
			maps.put("Accept", "application/octet-stream");
			downloadImage(remotepath,maps);
		} else {
		//	image.setImageResource(default_res);
			Bitmap bitmap = ImageCache.getInstance().get(uri1.getPath());	
			image.setImageBitmap(bitmap);
		}

		image.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	/**
	 * 下载图片
	 * 
	 * @param remoteFilePath
	 */
	private void downloadImage(final String remoteFilePath,final Map<String,String> headers) {
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setCanceledOnTouchOutside(false);
		pd.setMessage("下载图片: 0%");
		pd.show();

			emMessage = EMChatManager.getInstance().getMessage(sendid,chatType, msgid);	    	
		if(emMessage==null)
		{
			pd.dismiss();
		//	image.setImageResource(default_res);
			Bitmap bitmap = ImageCache.getInstance().get(uri1.getPath());	
			image.setImageBitmap(bitmap);			
			return;
		} 
	//	PathUtil.curPlayId = sendid;		
		final ImageMessageBody picbody = (ImageMessageBody) emMessage.getBody();
		localFilePath = picbody.getLocalUrl();
		picbody.setDownloadCallback(new msgCallBack() {

			@Override
			public void onError(int code, String message) {

			}

			@Override
			public void onProgress(final int progress, String status) {
		//		Log.d("ease Progress: " + progress);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						pd.setMessage("下载图片: " + progress + "%");
					}
				});
			}

			@Override
			public void onSuccess(int code, Object context) {			
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						DisplayMetrics metrics = new DisplayMetrics();
						getWindowManager().getDefaultDisplay().getMetrics(metrics);
						int screenWidth = metrics.widthPixels;
						int screenHeight = metrics.heightPixels;

						bitmap = ImageUtils.decodeScaleImage1(localFilePath, screenWidth, screenHeight);
						if (bitmap == null) {
						//	image.setImageResource(default_res);
							Bitmap bitmap1 = ImageCache.getInstance().get(uri1.getPath());	
							image.setImageBitmap(bitmap1);							
						} else {
							image.setImageBitmap(bitmap);
							ImageCache.getInstance().put(localFilePath, bitmap);
							isDownloaded = true;

						}
						if (pd != null) {
							pd.dismiss();
						}
					}
				});		
			}
			@Override
			public void onFailure(int errorCode, String message) {
		//		Log.e("### offline file transfer error:" + message);
				File file = new File(localFilePath);
				if (file.exists()) {
					file.delete();
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						pd.dismiss();
					//	image.setImageResource(default_res);
						Bitmap bitmap = ImageCache.getInstance().get(uri1.getPath());	
						image.setImageBitmap(bitmap);						
					}
				});
			}

		});		


		new Thread(new Runnable() {
			@Override
			public void run() {
				EMSendManager.fetchMessageFile(emMessage);				
			}
		}).start();

	}

	@Override
	public void onBackPressed() {

		if(pd!=null)
		{
			pd.dismiss();
		}		
		finish();
	}
}
