package com.lianxin.pubqq.chat;

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

import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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.entity.EMMessage;
import com.lianxin.panqq.chat.entity.VideoMessageBody;
import com.lianxin.panqq.main.PathUtil;
import com.lianxin.panqq.client.callback.msgCallBack;

/**
 * 展示视频内容
 */
public class ShowVideoActivity extends BaseActivity implements OnTouchListener {

	private RelativeLayout loadingLayout;
	private ProgressBar progressBar;
	private String localFilePath;

	private int sendid = 10001;	
	private int msgid = 10001;
	private int chatType = 1;	
	private  EMMessage emMessage;	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_showvideo);
		// 版本判断。当手机系统大于 23 时，才有必要去判断权 限是否获取
		if (Build.VERSION.SDK_INT >= 23) {
//return;
		}
		loadingLayout = (RelativeLayout) findViewById(R.id.loading_layout);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
	//	loadingLayout.setVisibility(View.VISIBLE);		
		localFilePath = getIntent().getStringExtra("localpath");
		String remotepath = getIntent().getStringExtra("remotepath");
		String secret = getIntent().getStringExtra("secret");
		sendid = getIntent().getIntExtra("sendid",10002);
		msgid = getIntent().getIntExtra("message", 1);	
		chatType = getIntent().getIntExtra("chattype", 1);			
		System.err.println("show video view file:" + localFilePath
				+ " remotepath:" + remotepath + " secret:" + secret);
		
			final int seid = sendid;
		//	final int reid = nDestId;
			final int msid = msgid;	
			final String filepath = localFilePath;			
			  new Thread(){
			        @Override
			        public void run() {
			            super.run();
			            Looper.prepare();
			            try {
			                Toast.makeText(ShowVideoActivity.this,"seid:"+seid+"msgid:"+msid+"/nfilepath:"+filepath,Toast.LENGTH_SHORT).show();		            	
			            }catch (Exception e) {

			            }
			            Looper.loop();
			        }
			    }.start();
		if (Build.VERSION.SDK_INT >= 23) {
//return;
		}	
		if (localFilePath != null && new File(localFilePath).exists()) {
			/*Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(localFilePath)),
					"video/mp4");
			startActivity(intent);
			finish();*/
			Intent intent = new Intent(Intent.ACTION_VIEW);
			// 獲取系統版本
			int currentapiVersion = android.os.Build.VERSION.SDK_INT;
			if (currentapiVersion < 24) {
				// 从文件中创建uri
				Uri uri = Uri.fromFile(new File(localFilePath));
				//intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				intent.setDataAndType(uri,"video/*");				
			} else {
				// 兼容android7.0 使用共享文件的形式
				ContentValues contentValues = new ContentValues(1);
				contentValues.put(MediaStore.Images.Media.DATA,
						new File(localFilePath).getAbsolutePath());
				Uri uri = MyApp
						.getInstance()
						.getContentResolver()
						.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								contentValues);
				//intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				intent.setDataAndType(uri,"video/*");	
				
			}	
			startActivity(intent);
			finish();			
		} else if (!TextUtils.isEmpty(remotepath) && !remotepath.equals("null")) {
			System.err.println("download remote video file");
			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");
			downloadVideo(remotepath, maps);
		} else {//没有用remotepath传递数据
			System.err.println("download remote video file");
			Map<String, String> maps = new HashMap<String, String>();

			downloadVideo(remotepath, maps);
		}

	}

	/**
	 * 下载视频文件
	 */
	private void downloadVideo(final String remoteUrl,
			final Map<String, String> header) {
	
		emMessage = EMChatManager.getInstance().getMessage(sendid,chatType, msgid);			
		if(emMessage==null)
		{
	//		pd.dismiss();
	//		image.setImageResource(default_res);			
			return;
		}  

		PathUtil.curPlayId = sendid;		
		final VideoMessageBody vidbody = (VideoMessageBody) emMessage.getBody();
		localFilePath = vidbody.getLocalUrl();		
		if (TextUtils.isEmpty(localFilePath)) {

			return;			
		}

		if (new File(localFilePath).exists()) {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(localFilePath)),
					"video/mp4");
			startActivity(intent);
			finish();
			return;
		}

		System.err.println("download view file ...");
		loadingLayout.setVisibility(View.VISIBLE);

		vidbody.setDownloadCallback(new msgCallBack() {

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

			}

			@Override
			public void onProgress(final int progress, String status) {
				//Log.d("ease video progress:" + progress);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						progressBar.setProgress(progress);

					}
				});
			}

			@Override
			public void onSuccess(int code, Object context) {			
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						loadingLayout.setVisibility(View.GONE);
						progressBar.setProgress(0);
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(
								Uri.fromFile(new File(localFilePath)),
								"video/mp4");
						startActivity(intent);
						finish();
					}
				});	
			}
			@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() {

					}
				});
			}

		});
		new Thread(new Runnable() {

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

	}

	@Override
	public void onBackPressed() {
		finish();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return false;
	}

}
