package com.lianxin.pubqq.chat;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.R;
import com.lianxin.pubqq.main.MyApp;
import com.lianxin.panqq.chat.BaseActivity;
import com.lianxin.panqq.main.EMChatManager;
import com.lianxin.panqq.main.EMSendManager;
import com.lianxin.panqq.chat.EMConversation;
import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.chat.entity.NormalFileMessageBody;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.client.callback.msgCallBack;
import com.lianxin.panqq.utils.UriUtils;

public class UploadFileActivity extends BaseActivity implements OnClickListener {
    static final int FILE_ONLINE = 1;  //在线等待发送文件
    static final int FILE_OFFLINE = 2; //离线发送文件（先存到服务器）
    static final int FILE_SHARE = 3; //群共享文件（存到服务器）	
	private ProgressBar progressBar;
	private TextView txt_title;
	private TextView txt_filename;
	private TextView txt_status;	
	private Button btn_send;	
	private Button btn_cancel;
	private Uri uri;
	private String filePath;	
	private int sendid = 10002;
	private int destid = 10001;
	private int chatType = 2;
	private int nMode = 0;	
	private int sendMode = 1;	//0:不需要确定发送就直接发送    1:需要确定发送
	private EMMessage emMessage;	
	private  EMConversation conVersation;	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_file);

		initView();
		initData();
		setListener();		
		if(nMode!=1&&sendMode==0)		
		    uploadFile();		

	}
	
	protected void initView() {
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		txt_title = (TextView)findViewById(R.id.titleView);
		txt_filename = (TextView)findViewById(R.id.nameView);
		txt_status = (TextView)findViewById(R.id.statusView);
		btn_send = (Button)findViewById(R.id.btn_send);
		btn_cancel = (Button)findViewById(R.id.btn_cancel);		
	}
	
	protected void initData() {
		
		sendid = getIntent().getIntExtra("sendid",10002);
		destid = getIntent().getIntExtra("destid", 10001);
		chatType = getIntent().getIntExtra("chattype", 5);			
		nMode = getIntent().getIntExtra("mode", 2);	
		uri = getIntent().getParcelableExtra("uri"); //隐式调用Intent.ACTION_GET_CONTENT所得
		filePath = getIntent().getStringExtra("filepath"); //显式调用自定义FileSelect所得		
		// 本地存在，直接显示本地的图片
		//if (filePath == "" && uri != null) {		
		if ( uri != null) {
			final int seid = sendid;
			final int trantype = 10;		
			  new Thread(){
			        @Override
			        public void run() {
			            super.run();
			            Looper.prepare();
			            try {
			                Toast.makeText(MyApp.getInstance(),"sendid:"+seid+"trantype:"+trantype,Toast.LENGTH_LONG).show();		            	
			            }catch (Exception e) {

			            }
			            Looper.loop();
			        }
			    }.start();				
			filePath = UriUtils.getFilePathByUri(UploadFileActivity.this, uri);							
		}
		if(nMode==1){
			txt_title.setText("在线文件");
		}else if(nMode==2){
			txt_title.setText("离线文件");		
		}else{
			txt_title.setText("共享文件");		
		}
		
		if (filePath != null && new File(filePath).exists()) {
			
		}else{
			return;			
		}		
		txt_filename.setText(filePath);		
		emMessage = EMMessage.createSendMessage(sendid,EMMessage.MsgType.MSG_BIGFILE);	
		conVersation = EMChatManager.getInstance().getConversation(destid,chatType);	
		long UserTimeStamp = conVersation.getTimeStamp();
		NormalFileMessageBody filebody = new NormalFileMessageBody(new File(filePath),UserTimeStamp);
		if(nMode==1)		
			filebody.setIsOff(0);
		else		
			filebody.setIsOff(0x23);		
		emMessage.addBody(filebody);	
		emMessage.setChatType(chatType);			
		emMessage.setSendRecvId(destid);		
		emMessage.setSendId(sendid);
		emMessage.setMsgTime(UserTimeStamp);
		
		if(nMode==1)		
		conVersation.addSendMessage(emMessage);		
	}
	
	protected void setListener() {

		btn_send.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);		

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_cancel) {
			Utils.finish(UploadFileActivity.this);
			//finish();
		} else if (id == R.id.btn_send) {
			if (nMode == 1)
				sendBigFile();
			else
				uploadFile();
		}
	}	
	
	protected void uploadFile() {
		if (TextUtils.isEmpty(GloableParams.m_szServerIp)) {
			return;
		}
		if (filePath != null && new File(filePath).exists()) {

		} else {
			return;
		}
		if ( emMessage == null ) {
			return;
		}		
		// 上传文件
		// new Thread(new Runnable() {
		// public void run() {
		EMSendManager.UploadBigFile(emMessage, new msgCallBack() {
			@Override
			public void onError(int code, final String message) {
				runOnUiThread(new Runnable() {
					public void run() {
						txt_status.setText(message);
					}
				});
			}

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

			@Override
			public void onSuccess(int code, Object context) {
				runOnUiThread(new Runnable() {
					public void run() {
						// 上传成功，才加到消息列表
						progressBar.setProgress(100);
						addtoView();
						Utils.finish(UploadFileActivity.this);
					}
				});
			}

			@Override
			public void onFailure(int errorCode, final String message) {
				runOnUiThread(new Runnable() {
					public void run() {
						txt_status.setText(message);
					}
				});
			}
		});
		// }
		// }).start();
	}
	
	protected void sendBigFile() {

		if (filePath != null && new File(filePath).exists()) {

		} else {
			return;
		}
		if ( emMessage == null ) {
			return;
		}		
		// 上传文件
		// new Thread(new Runnable() {
		// public void run() {
		EMSendManager.SendBigFile(emMessage, new msgCallBack() {
			@Override
			public void onError(int code, final String message) {
				runOnUiThread(new Runnable() {
					public void run() {
						txt_status.setText(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() {
						// 上传成功，才加到消息列表
						progressBar.setProgress(100);
						//addtoView();
						Utils.finish(UploadFileActivity.this);
					}
				});
			}

			@Override
			public void onFailure(int errorCode, final String message) {
				runOnUiThread(new Runnable() {
					public void run() {
						txt_status.setText(message);
					}
				});
			}
		});
		// }
		// }).start();
	}	
	
	protected void addtoView() {
		if(nMode!=1)  //离线文件和共享文件，都是先上传文件再发送消息
		    conVersation.addSendMessage(emMessage);		
	}	
}
