package com.lianxin.pubqq.chat;

import java.io.File;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.chat.BaseActivity;
import com.lianxin.panqq.main.EMChatManager;
import com.lianxin.panqq.main.EMSendManager;
import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.chat.entity.NormalFileMessageBody;
import com.lianxin.panqq.client.callback.msgCallBack;

public class ShowNormalFileActivity extends BaseActivity {
	private ProgressBar progressBar;
	private File file;
	private   EMMessage emMessage;	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_show_file);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		
		int sendid = getIntent().getIntExtra("sendid",10002);
		//int msgid = getIntent().getIntExtra("message", 1);	
		//sendid = getIntent().getIntExtra("sendid",10002);
		int recvid = getIntent().getIntExtra("recvid", 10001);		
		int chatType = getIntent().getIntExtra("chattype", 5);				
		int destid = recvid;		
		if(chatType<5)
			destid = sendid;
		int msgid = getIntent().getIntExtra("message", 1);		
		//emMessage = EMChatManager.getInstance().getMessage(sendid,EMMessage.ChatType.ChatType_USER,msgid); 	
		emMessage = EMChatManager.getInstance().getMessage(destid,chatType,msgid);		
		if(emMessage==null)
		{
		//	progressBar.dismiss();
		//	image.setImageResource(default_res);			
			return;
		}  	

		final NormalFileMessageBody filebody = (NormalFileMessageBody) emMessage.getBody();
		file = new File(filebody.getLocalUrl());			
		filebody.setDownloadCallback(new msgCallBack() {

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

			}

			@Override
			public void onProgress(final int progress, String status) {
				runOnUiThread(new Runnable() {
					public void run() {
						progressBar.setProgress(progress);
					}
				});				
			}

			@Override
			public void onSuccess(int code, Object context) {			
				runOnUiThread(new Runnable() {
					public void run() {					
					//	FileUtils.openFile(file, ShowNormalFileActivity.this);
						finish();
					}
				});	
			}
			@Override
			public void onFailure(int errorCode, String message) {
				final String msg = message;
				runOnUiThread(new Runnable() {
					public void run() {					
						if(file != null && file.exists())
							file.delete();
						Toast.makeText(ShowNormalFileActivity.this, "下载文件失败: "+msg, 0).show();
						finish();
					}
				});
			}

		});			
		//下载文件
		new Thread(new Runnable() {
			public void run() {

				EMSendManager.fetchMessageFile(emMessage);
			}
		}).start();
		
	}
}
