package com.yixia.camera.demo.ui.record;

import java.io.File;
import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wechat01.R;
import com.yixia.camera.demo.VCameraDemoApplication;
import com.yixia.camera.demo.common.CommonIntentExtra;
import com.yixia.camera.demo.po.POThemeSingle;
import com.yixia.camera.demo.service.AssertService;
import com.yixia.camera.demo.ui.BaseActivity;
import com.yixia.camera.demo.ui.record.helper.ThemeHelper;
import com.yixia.camera.demo.ui.record.views.ThemeGroupLayout;
import com.yixia.camera.demo.ui.record.views.ThemeSufaceView;
import com.yixia.camera.demo.ui.record.views.ThemeView;
import com.yixia.camera.demo.utils.ConvertToUtils;
import com.yixia.camera.demo.utils.IsUtils;
import com.yixia.camera.demo.utils.ToastUtils;
import com.yixia.camera.model.MediaObject;
import com.yixia.camera.model.MediaThemeObject;
import com.yixia.camera.util.DeviceUtils;
import com.yixia.camera.util.FileUtils;
import com.yixia.camera.util.StringUtils;
import com.yixia.videoeditor.adapter.UtilityAdapter;

/**
 * 瑙嗛棰勮
 * 
 * @author tangjun@yixia.com
 *
 */
public class MediaPreviewActivity extends BaseActivity implements
		OnClickListener, UtilityAdapter.OnNativeListener {

	/** 寮€濮嬭浆鐮?*/
	private static final int HANDLER_ENCODING_START = 100;
	/** 杞爜杩涘害 */
	private static final int HANDLER_ENCODING_PROGRESS = 101;
	/** 杞爜缁撴潫 */
	private static final int HANDLER_ENCODING_END = 102;
	/** 鏃犱富棰樻斁鐨勪綅缃?*/
	private final static int NO_THEME_INDEX = 0;

	/** 鎾斁鎸夐挳銆佷富棰橀煶閲忔寜閽?*/
	private ImageView mPlayStatus;
	/** 涓婁竴姝ャ€佷笅涓€姝?*/
	private TextView mTitleLeft, mTitleNext, mTitleText, mVideoPreviewMusic;
	/** 涓婚闊充箰锛屽師澹伴煶 */
	private CheckBox mThemeVolumn, mVideoVolumn;
	/** 姝e湪鍔犺浇 */
	private View mLoadingView;
	/** 涓婚銆佹护闀滃鍣?*/
	private View mThemeLayout, mFilterLayout;

	/** 涓婚瀹瑰櫒 */
	private ThemeGroupLayout mThemes, mFilters;
	/** MV涓婚 */
	private ThemeSufaceView mThemeSufaceView;

	/** 涓婚缂撳瓨鐨勭洰褰?*/
	private File mThemeCacheDir;
	/** 褰撳墠涓婚 */
	private POThemeSingle mCurrentTheme;

	/** 涓婚鍒楄〃 */
	private ArrayList<POThemeSingle> mThemeList;
	/** 婊ら暅鍒楄〃 */
	private ArrayList<POThemeSingle> mFilterList;

	/** 瀵兼紨绛惧悕鍥剧墖 */
	private String mAuthorBitmapPath;
	/** 瀵煎嚭瑙嗛锛屽鍑哄皝闈?*/
	private String mVideoPath, mCoverPath;
	/** 涓存椂鍚堝苟ts娴?*/
	private String mVideoTempPath;
	/** 褰撳墠闊充箰璺緞 */
	private String mCurrentMusicPath;
	/** 褰撳墠闊充箰鍚嶇О */
	private String mCurrentMusicTitle;
	/** 褰撳墠闊充箰鍚嶇О */
	private String mCurrentMusicName;
	/** 鏄惁闇€瑕佸洖澶嶆挱鏀?*/
	private boolean mNeedResume;
	/** 鏄惁鍋滄鎾斁 */
	private boolean mStopPlayer;
	/** 鏄惁姝e湪杞爜 */
	private boolean mStartEncoding;
	/** 绐椾綋瀹藉害 */
	private int mWindowWidth;
	/** 鍒嗗潡杈硅窛锛岄粯璁?0dip */
	private int mLeftMargin;
	/** 瑙嗛鏃堕暱 */
	private int mDuration;
	/** 瑙嗛淇℃伅 */
	private MediaObject mMediaObject;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		VCameraDemoApplication.getInstance().addActivity(this);
		mMediaObject = (MediaObject) getIntent().getSerializableExtra(
				CommonIntentExtra.EXTRA_MEDIA_OBJECT);
		if (mMediaObject == null) {
			Toast.makeText(this, R.string.record_read_object_faild,
					Toast.LENGTH_SHORT).show();
			finish();
			overridePendingTransition(R.anim.push_bottom_in,
					R.anim.push_bottom_out);
			return;
		}

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 闃叉閿佸睆
		prepareActivity();
		prepareViews();
	}

	/** 棰勫鐞嗗弬鏁?*/
	private boolean prepareActivity() {
		// 鍔犺浇榛樿鍙傛暟
		mWindowWidth = DeviceUtils.getScreenWidth(this);
		// 鑾峰彇浼犲叆鍙傛暟
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()) && !isExternalStorageRemovable())
			mThemeCacheDir = new File(getExternalCacheDir(), "Theme");
		else
			mThemeCacheDir = new File(getCacheDir(), "Theme");
		mLeftMargin = ConvertToUtils.dipToPX(this, 8);

		mVideoPath = mMediaObject.getOutputVideoPath();
		if (StringUtils.isNotEmpty(mVideoPath)) {
			mCoverPath = mVideoPath.replace(".mp4", ".jpg");
		}
		mVideoTempPath = getIntent().getStringExtra("output");

		return true;
	}

	/** 棰勫鐞哢I鐩稿叧 */
	private void prepareViews() {
		setContentView(R.layout.activity_media_preview);
		// 缁戝畾鎺т欢
		mPlayStatus = (ImageView) findViewById(R.id.play_status);
		mThemeSufaceView = (ThemeSufaceView) findViewById(R.id.preview_theme);
		mTitleLeft = (TextView) findViewById(R.id.titleLeft);
		mTitleNext = (TextView) findViewById(R.id.titleRight);
		mTitleText = (TextView) findViewById(R.id.titleText);
		mVideoPreviewMusic = (TextView) findViewById(R.id.video_preview_music);
		mThemes = (ThemeGroupLayout) findViewById(R.id.themes);
		mFilters = (ThemeGroupLayout) findViewById(R.id.filters);
		mThemeVolumn = (CheckBox) findViewById(R.id.video_preview_theme_volume);
		mVideoVolumn = (CheckBox) findViewById(R.id.video_preview_video_volume);
		mLoadingView = findViewById(R.id.loading);
		mThemeLayout = findViewById(R.id.theme_layout);
		mFilterLayout = findViewById(R.id.filter_layout);

		mTitleLeft.setOnClickListener(this);
		mTitleNext.setOnClickListener(this);
		mThemeSufaceView.setOnComplateListener(mOnComplateListener);
		mThemeSufaceView.setOnClickListener(this);
		findViewById(R.id.tab_theme).setOnClickListener(this);
		findViewById(R.id.tab_filter).setOnClickListener(this);
		mThemeVolumn.setOnClickListener(this);
		mVideoVolumn.setOnClickListener(this);

		mTitleText.setText(R.string.record_camera_preview_title);
		mTitleNext.setText(R.string.record_camera_preview_next);

		// 璁剧疆涓婚棰勮榛樿鍙傛暟
		mThemeSufaceView.setIntent(getIntent());
		mThemeSufaceView.setOutputPath(mVideoPath);// 杈撳嚭鏂囦欢
		mThemeSufaceView.setMediaObject(mMediaObject);
		if (FileUtils.checkFile(mThemeCacheDir)) {
			mThemeSufaceView.setFilterCommomPath(new File(mThemeCacheDir,
					ThemeHelper.THEME_VIDEO_COMMON).getAbsolutePath());
		}
		/** 璁剧疆鎾斁鍖哄煙 */
		View preview_layout = findViewById(R.id.preview_layout);
		LinearLayout.LayoutParams mPreviewParams = (LinearLayout.LayoutParams) preview_layout
				.getLayoutParams();
		mPreviewParams.height = DeviceUtils.getScreenWidth(this);
		loadThemes();
	}

	@Override
	public void onResume() {
		super.onResume();
		UtilityAdapter.registerNativeListener(this);
		if (mThemeSufaceView != null && mNeedResume && mCurrentTheme != null) {
			restart();
		}
		mNeedResume = false;
	}

	@Override
	public void onPause() {
		super.onPause();
		UtilityAdapter.registerNativeListener(null);
		if (mThemeSufaceView != null && mThemeSufaceView.isPlaying()) {
			mNeedResume = true;
			releaseVideo();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.titleLeft:
			finish();
			break;
		case R.id.titleRight:
			startEncoding();
			break;
		case R.id.preview_theme:// 鐐瑰嚮鏆傚仠瑙嗛鎾斁
			if (isPlaying())
				stopVideo();
			else
				startVideo();
			break;
		case R.id.video_preview_theme_volume:// 闈欓煶涓婚闊?			// 闅愯棌鍔ㄧ敾
			ToastUtils
					.showToastImage(
							this,
							mThemeVolumn.isChecked() ? R.drawable.priview_theme_volumn_close
									: R.drawable.priview_theme_volumn_open);
			mThemeSufaceView.setThemeMute(mThemeVolumn.isChecked());
			restart();
			break;
		case R.id.video_preview_video_volume:// 闈欓煶鍘熷0
			ToastUtils
					.showToastImage(
							this,
							mVideoVolumn.isChecked() ? R.drawable.priview_orig_volumn_close
									: R.drawable.priview_orig_volumn_open);
			mThemeSufaceView.setOrgiMute(mVideoVolumn.isChecked());
			restart();
			break;
		case R.id.tab_theme:
			mThemeLayout.setVisibility(View.VISIBLE);
			mFilterLayout.setVisibility(View.GONE);
			break;
		case R.id.tab_filter:
			mThemeLayout.setVisibility(View.GONE);
			mFilterLayout.setVisibility(View.VISIBLE);
			break;
		}
	}

	/** 寮€濮嬭浆鐮?*/
	private void startEncoding() {
		// 妫€娴嬬鐩樼┖闂?		// if (FileUtils.showFileAvailable() < 200) {
		// Toast.makeText(this, R.string.record_camera_check_available_faild,
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		stopVideo();

		// 鏇存柊闈欓煶
		if (mMediaObject != null && mMediaObject.mThemeObject != null) {
			mMediaObject.mThemeObject.mThemeMute = mThemeVolumn.isChecked();
			mMediaObject.mThemeObject.mOrgiMute = mVideoVolumn.isChecked();
		}
		// 妫€娴嬫槸鍚﹂渶瑕侀噸鏂扮紪璇?		mStartEncoding = true;
		mHandler.removeMessages(HANDLER_ENCODING_START);
		mHandler.removeMessages(HANDLER_ENCODING_PROGRESS);
		mHandler.removeMessages(HANDLER_ENCODING_END);
		mHandler.sendEmptyMessage(HANDLER_ENCODING_START);
	}

	/** 鍔犺浇涓婚 */
	private void loadThemes() {
		if (isFinishing() || mStartEncoding)
			return;

		new android.os.AsyncTask<Void, Void, File>() {

			@Override
			protected File doInBackground(Void... params) {
				// 棰勫鐞嗕富棰?				while (AssertService.isRunning()) {
					SystemClock.sleep(500);
				}

				// 棰勫鐞嗕富棰橈紙瑙e帇鏇存柊涓婚鍖咃級
				File result = ThemeHelper.prepareTheme(
						MediaPreviewActivity.this, mThemeCacheDir);
				if (result != null) {
					// 涓婚鍒楄〃
					mThemeList = ThemeHelper.parseTheme(
							MediaPreviewActivity.this, mThemeCacheDir,
							ThemeHelper.THEME_MUSIC_VIDEO_ASSETS,
							R.array.theme_order);

					// 绌轰富棰?					POThemeSingle orgiTheme = ThemeHelper.loadThemeJson(
							mThemeCacheDir, new File(mThemeCacheDir,
									ThemeHelper.THEME_EMPTY));
					if (orgiTheme != null)
						mThemeList.add(NO_THEME_INDEX, orgiTheme);
				}

				// 鍔犺浇婊ら暅
				mFilterList = ThemeHelper.parseTheme(MediaPreviewActivity.this,
						mThemeCacheDir, ThemeHelper.THEME_FILTER_ASSETS,
						R.array.theme_filter_order);

				// 鐢熸垚绛惧悕
				mAuthorBitmapPath = ThemeHelper
						.updateVideoAuthorLogo(
								mThemeCacheDir,
								getString(R.string.record_camera_author,
										getString(R.string.app_name)
												+ " By Juns Allen"), false);
				return result;
			}

			@Override
			protected void onPostExecute(File result) {
				super.onPostExecute(result);
				File themeDir = result;
				if (themeDir != null && !isFinishing() && mThemeList != null
						&& mThemeList.size() > 1) {
					/** 寰幆娣诲姞鍗曚釜涓婚鍒颁富棰樺鍣ㄤ腑 */
					mThemes.removeAllViews();

					String themeName = getIntent().getStringExtra("theme");
					int defaultIndex = NO_THEME_INDEX, index = 0;
					if (mCurrentTheme != null) {
						themeName = mCurrentTheme.themeName;
					}
					for (POThemeSingle theme : mThemeList) {
						addThemeItem(theme, -1);// 椤哄簭娣诲姞
						if (StringUtils.isNotEmpty(themeName)
								&& IsUtils.equals(theme.themeName, themeName)) {
							defaultIndex = index;
						}
						index++;
					}

					// 婊ら暅
					mFilters.removeAllViews();
					for (POThemeSingle theme : mFilterList) {
						addThemeItem(mFilters, theme, -1);// 椤哄簭娣诲姞
					}

					mCurrentTheme = null;
					mThemes.getChildAt(defaultIndex).performClick();// 榛樿閫変腑鏃犱富棰?				}
			}

		}.execute();
	}

	private ThemeView addThemeItem(ThemeGroupLayout layout,
			POThemeSingle theme, int index) {
		ThemeView themeView = new ThemeView(MediaPreviewActivity.this, theme);
		if (theme.themeIconResource > 0) {
			themeView.getIcon().setImageResource(theme.themeIconResource);
		} else {
			if (StringUtils.isNotEmpty(theme.themeIcon)) {
				themeView.getIcon().setImagePath(theme.themeIcon);
			}
		}

		themeView.setOnClickListener(mThemeClickListener);
		themeView.setTag(theme);
		// Logger.e("[MediaPreviewActivity]addThemeItem..." +
		// theme.themeDisplayName + " themeFolder:" + theme.themeFolder);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);// mThemeItemWH,
														// mThemeItemWH
		lp.leftMargin = mLeftMargin;
		if (index == -1)
			layout.addView(themeView, lp);
		else
			layout.addView(themeView, index, lp);
		return themeView;
	}

	/** 娣诲姞褰撲釜涓婚鍒癠I涓?*/
	private ThemeView addThemeItem(POThemeSingle theme, int index) {
		return addThemeItem(mThemes, theme, index);
	}

	/** 閲嶆柊鎾斁 */
	private synchronized void restart() {
		mStopPlayer = false;
		mHandler.removeMessages(UtilityAdapter.NOTIFYVALUE_PLAYFINISH);
		mHandler.sendEmptyMessageDelayed(UtilityAdapter.NOTIFYVALUE_PLAYFINISH,
				100);
	}

	private void releaseVideo() {
		mThemeSufaceView.pauseClearDelayed();
		mThemeSufaceView.release();
		mPlayStatus.setVisibility(View.GONE);
	}

	/** 寮€濮嬫挱鏀?*/
	private void startVideo() {
		mStopPlayer = false;
		mThemeSufaceView.start();
		mPlayStatus.setVisibility(View.GONE);
	}

	/** 鏆傚仠鎾斁 */
	private void stopVideo() {
		mStopPlayer = true;
		mThemeSufaceView.pause();
		mPlayStatus.setVisibility(View.VISIBLE);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_ENCODING_START:
				if (!isFinishing()) {
					showProgress("",
							getString(R.string.record_preview_encoding));
					// WindowManager.LayoutParams lp =
					// dialog.getWindow().getAttributes();
					// lp.y = -ConvertToUtils.dipToPX(MediaPreviewActivity.this,
					// 49 + 30);
					// dialog.getWindow().setAttributes(lp);
					// showProgressLayout(false, false,
					// getString(R.string.progressbar_message_preview_making));
					releaseVideo();
					mThemeSufaceView.startEncoding();
					sendEmptyMessage(HANDLER_ENCODING_PROGRESS);
				}
				break;
			case HANDLER_ENCODING_PROGRESS:// 璇诲彇杩涘害
				int progress = UtilityAdapter
						.FilterParserInfo(UtilityAdapter.FILTERINFO_PROGRESS);
				if (mProgressDialog != null) {
					mProgressDialog.setMessage(getString(
							R.string.record_preview_encoding_format, progress));
				}
				if (progress < 100)
					sendEmptyMessageDelayed(HANDLER_ENCODING_PROGRESS, 200);
				else {
					sendEmptyMessage(HANDLER_ENCODING_END);
				}
				break;
			case HANDLER_ENCODING_END:
				mDuration = UtilityAdapter
						.FilterParserInfo(UtilityAdapter.FILTERINFO_TOTALMS);
				mThemeSufaceView.release();
				onEncodingEnd();
				break;
			case UtilityAdapter.NOTIFYVALUE_BUFFEREMPTY:
				showLoading();
				break;
			case UtilityAdapter.NOTIFYVALUE_BUFFERFULL:
				hideLoading();
				break;
			case UtilityAdapter.NOTIFYVALUE_PLAYFINISH:
				/** 鎾斁瀹屾垚鏃舵姤鍛?*/
				if (!isFinishing() && !mStopPlayer) {
					showLoading();
					mThemeSufaceView.release();
					mThemeSufaceView.initFilter();
					mPlayStatus.setVisibility(View.GONE);
				}
				break;
			case UtilityAdapter.NOTIFYVALUE_HAVEERROR:
				/** 鏃犳硶鎾斁鏃舵姤鍛?*/
				if (!isFinishing()) {
					Toast.makeText(MediaPreviewActivity.this,
							R.string.record_preview_theme_load_faild,
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	/** 杞爜瀹屾垚 */
	private void onEncodingEnd() {
		hideProgress();
		mStartEncoding = false;
		startActivity(new Intent(this, VideoPlayerActivity.class).putExtra(
				"path", mVideoPath));
	}

	/** 鏄剧ず鍔犺浇涓?*/
	private void showLoading() {
		// showProgress("", getString(R.string.record_preview_building));
		if (mLoadingView != null)
			mLoadingView.setVisibility(View.VISIBLE);
	}

	/** 闅愯棌鍔犺浇涓?*/
	private void hideLoading() {
		if (mLoadingView != null)
			mLoadingView.setVisibility(View.GONE);
	}

	/** 鏄惁姝e湪鎾斁 */
	private boolean isPlaying() {
		return mThemeSufaceView.isPlaying();
	}

	/** 鍝嶅簲涓婚鐐瑰嚮浜嬩欢 */
	private OnClickListener mThemeClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			POThemeSingle theme = (POThemeSingle) v.getTag();
			if (theme == null || mMediaObject == null)
				return;

			if (StringUtils.isNotEmpty(mAuthorBitmapPath)
					&& (mCurrentTheme == null || !IsUtils.equals(
							mCurrentTheme.themeName, theme.themeName))) {
				String key = theme.themeName;
				((ThemeGroupLayout) v.getParent()).mObservable
						.notifyObservers(key);

				mCurrentTheme = theme;

				if (mMediaObject.mThemeObject == null)
					mMediaObject.mThemeObject = new MediaThemeObject();

				if (theme.isMV()) {
					mMediaObject.mThemeObject.mMVThemeName = theme.themeName;
					mMediaObject.mThemeObject.mMusicThemeName = theme.musicName;
					mThemeSufaceView.reset();
					mThemeSufaceView.setMVPath(theme.themeFolder);
					mThemeSufaceView.setTheme(theme);
					mThemeSufaceView.setVideoEndPath(mAuthorBitmapPath);// 绛惧悕
					mThemeSufaceView.setInputPath(mVideoTempPath);// 杈撳叆鏂囦欢
					// 娣诲姞闊充箰
					mCurrentMusicPath = mCurrentTheme.musicPath;
					mCurrentMusicTitle = mCurrentTheme.musicTitle;
					mCurrentMusicName = mCurrentTheme.musicName;
					mThemeSufaceView.setMusicPath(mCurrentMusicPath);

					updateMusicTextView();

					// 娓呯┖闈欓煶鐘舵€?					mThemeVolumn.setChecked(false);

					// 娓呴櫎婊ら暅鐨勯€変腑鐘舵€?					if (mFilters != null) {
						mFilters.mObservable
								.notifyObservers(POThemeSingle.THEME_EMPTY);
					}
				}

				// 婊ら暅
				if (theme.isFilter()) {
					mMediaObject.mThemeObject.mFilterThemeName = theme.themeName;
					mThemeSufaceView.setFilterPath(theme.getFilterPath());
				}

				restart();
			}
		}
	};

	/** 鏇存柊闊充箰鍚嶇О */
	private void updateMusicTextView() {
		if (StringUtils.isEmpty(mCurrentMusicTitle)) {
			mVideoPreviewMusic.setText(R.string.record_preview_music_nothing);
			mThemeVolumn.setVisibility(View.GONE);
		} else {
			mVideoPreviewMusic.setText(mCurrentMusicTitle);
			mThemeVolumn.setVisibility(View.VISIBLE);
		}
	}

	/** 鎾斁瀹屾垚 */
	private ThemeSufaceView.OnComplateListener mOnComplateListener = new ThemeSufaceView.OnComplateListener() {

		@Override
		public void onComplate() {
			if (!isFinishing()) {
				mThemeSufaceView.release();
			}
		}

	};

	public static boolean isExternalStorageRemovable() {
		if (DeviceUtils.hasGingerbread())
			return Environment.isExternalStorageRemovable();
		else
			return Environment.MEDIA_REMOVED.equals(Environment
					.getExternalStorageState());
	}

	@Override
	public void ndkNotify(int key, int value) {
		if (!isFinishing())
			mHandler.sendEmptyMessage(value);
	}
}