package com.gensee.fragement;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.config.ConfigApp;
import com.gensee.entity.PingEntity;
import com.gensee.holder.HongbaoHolder;
import com.gensee.holder.MedalPraiseHolder;
import com.gensee.media.IVideoIndication;
import com.gensee.player.Player;
import com.gensee.player.VideoRate;
import com.gensee.playerdemo.PlayerDemoActivityEx;
import com.gensee.playerdemo.R;
import com.gensee.routine.UserInfo;
import com.gensee.service.IMedalPraise;
import com.gensee.taskret.OnTaskRet;
import com.gensee.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import static com.gensee.player.OnPlayListener.INVITE_AUIDO;

//import com.gensee.entity.Reward;

@SuppressLint("ValidFragment")
public class ViedoFragment extends Fragment implements OnClickListener {

	private Player mPlayer;
	private View mView;
	private View mGSViedoView;
	private TextView txtVideo, txtAudio, txtMic, txtHand, txtIdc, txtReword, txtNickName, tvPraiseCount;
	private TextView btnHongbao, btnMedalRank,btnPraise,btnMyMedal;
	private Spinner spinnerRate;
	private SeekBar volumeSeekBar;
	private TextView volumeTextView;
	private Runnable handRun = null;
	private List<PingEntity> idcs;
	private HongbaoHolder hongbaoHolder;
	private MedalPraiseHolder medalPraiseHolder;
	private boolean isHongbaoEnable = false;

	public ViedoFragment(Player player) {
		this.mPlayer = player;
	}

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.imviedo, null);
		txtVideo = (TextView) mView.findViewById(R.id.txtVideo);
		txtAudio = (TextView) mView.findViewById(R.id.txtAudio);
		txtMic = (TextView) mView.findViewById(R.id.txtMic);
		txtHand = (TextView) mView.findViewById(R.id.txtHand);
		txtHand.setText("举手");

		spinnerRate = (Spinner) mView.findViewById(R.id.spinnerRate);
		initRateSelectView();

		txtIdc = (TextView) mView.findViewById(R.id.txtIdc);
		txtReword = (TextView) mView.findViewById(R.id.txtReword);
		txtNickName = (TextView) mView.findViewById(R.id.txtReName);
		btnHongbao = (TextView) mView.findViewById(R.id.btnHongbao);
		btnPraise = (TextView) mView.findViewById(R.id.btnPraise);
		tvPraiseCount = (TextView) mView.findViewById(R.id.tvPraiseCount);
		btnMedalRank = (TextView) mView.findViewById(R.id.btnMedalRank);
		btnMyMedal = (TextView) mView.findViewById(R.id.btnMyMedal);

		mGSViedoView = mView.findViewById(R.id.imvideoview);
//		mGSViedoView.setRenderMode(RenderMode.RM_FILL_CENTER_CROP);
		mGSViedoView.setOnClickListener(this);
		txtVideo.setOnClickListener(this);
		txtAudio.setOnClickListener(this);
		txtMic.setOnClickListener(this);
		txtHand.setOnClickListener(this);
		txtIdc.setOnClickListener(this);
		txtReword.setOnClickListener(this);
		txtNickName.setOnClickListener(this);
		btnHongbao.setOnClickListener(this);
		btnMedalRank.setOnClickListener(this);
		btnPraise.setOnClickListener(this);
		medalPraiseHolder.setPraiseCount(tvPraiseCount);
		medalPraiseHolder.setPraiseBtn(btnPraise);
		medalPraiseHolder.setBtnMyMedal(btnMyMedal);
		btnPraise.setText(getString(R.string.my_praise) + medalPraiseHolder.getSelfPraiseRemain());
		btnMyMedal.setText(getString(R.string.my_medal) + medalPraiseHolder.getSelfMedalTotal());
		mPlayer.setGSVideoView((IVideoIndication) mGSViedoView);
		
		volumeSeekBar = (SeekBar) mView.findViewById(R.id.volume_seekbar);
		volumeTextView = (TextView) mView.findViewById(R.id.volume_text);
		
		if (volumeSeekBar != null && mPlayer != null) {
			float currentVolume = mPlayer.getAudioVolume();
			int progress = (int)(currentVolume * 100);
			volumeSeekBar.setProgress(progress);
			updateVolumeDisplay(progress);
			
			volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
				@Override
				public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
					if (fromUser && mPlayer != null) {
						float volume = progress / 100.0f;
						mPlayer.setAudioVolume(volume);
						updateVolumeDisplay(progress);
					}
				}
				
				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
				}
				
				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
				}
			});
		}
		
		return mView;
	}

	public void setHongBaoHolder(HongbaoHolder hongbaoHolder) {
		this.hongbaoHolder = hongbaoHolder;
	}

	public void setMedalPraiseHolder(MedalPraiseHolder medalPraiseHolder) {
		this.medalPraiseHolder = medalPraiseHolder;
	}

	public void onJoin(boolean isJoined) {
		tvPraiseCount.setVisibility(medalPraiseHolder.isPraiseEnable()? View.VISIBLE:View.GONE);
		btnPraise.setVisibility(medalPraiseHolder.isPraiseEnable()? View.VISIBLE:View.GONE);
		btnMedalRank.setVisibility(medalPraiseHolder.isMedalEnable()? View.VISIBLE:View.GONE);
		btnMyMedal.setVisibility(medalPraiseHolder.isMedalEnable()? View.VISIBLE:View.GONE);
		medalPraiseHolder.getPraiseTotal();
		if (txtAudio != null) {
			txtAudio.setEnabled(isJoined);
			txtVideo.setEnabled(isJoined);
			txtHand.setEnabled(isJoined);
			txtIdc.setEnabled(isJoined);
			txtReword.setEnabled(isJoined);
			txtNickName.setEnabled(isJoined);
			if (isHongbaoEnable) {
				btnHongbao.setEnabled(isJoined);
				btnHongbao.setVisibility(View.VISIBLE);
			}
		}
		if (ConfigApp.mutePlay) {
			this.mPlayer.audioSet(true);
			txtAudio.setSelected(true);
			txtAudio.setText(R.string.audio_open);
		}
	}

	@SuppressLint("NewApi")
	public void setVideoViewVisible(boolean bVisible) {
		if (isAdded()) {
			if (bVisible) {
				mGSViedoView.setVisibility(View.VISIBLE);
			} else {
				mGSViedoView.setVisibility(View.GONE);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.imvideoview:
				int orientation = getActivity().getRequestedOrientation();
				if (orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
						|| orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
					orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
				} else {
					orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
				}
				getActivity().setRequestedOrientation(orientation);

				break;
			case R.id.txtAudio:
				if (mPlayer != null) {
					// isSelect 代表关闭状态，默认非关闭状态 即false
					if (v.isSelected()) {
						mPlayer.audioSet(false);
						v.setSelected(false);
						txtAudio.setText(R.string.audio_close);

					} else {
						mPlayer.audioSet(true);
						v.setSelected(true);
						txtAudio.setText(R.string.audio_open);
					}
				}
				break;
			case R.id.txtVideo:
				if (mPlayer != null) {
					// isSelect 代表关闭状态，默认非关闭状态 即false
					if (v.isSelected()) {
						mPlayer.videoSet(false);
						v.setSelected(false);
						txtVideo.setText(R.string.video_close);

					} else {
						mPlayer.videoSet(true);
						v.setSelected(true);
						txtVideo.setText(R.string.video_open);
					}
				}
				break;
			case R.id.txtMic:
				//停止说话
				if (mPlayer != null) {
					mPlayer.openMic(getActivity(), false, null);
					mPlayer.inviteAck((Integer) v.getTag(), false, null);
					if (getActivity() instanceof PlayerDemoActivityEx) {
						((PlayerDemoActivityEx) getActivity()).setInviteMediaType(INVITE_AUIDO, false);
					}
				}
				break;
			case R.id.txtHand:
				if (handRun != null) {
					txtHand.removeCallbacks(handRun);
				}
				if (!v.isSelected()) {
					mPlayer.handUp(true, null);
					txtHand.setSelected(true);
					handRun = new Runnable() {
						private int time = 60;

						@Override
						public void run() {
							txtHand.setText("举手(" + time + ")");
							time--;
							if (time < 0) {
								handDown();
							} else {
								txtHand.postDelayed(this, 1000);
							}
						}
					};
					txtHand.post(handRun);
				} else {
					handDown();
				}
				break;
			case R.id.txtIdc:
				int size = idcs == null ? 0 : idcs.size();
				if (size > 0) {
					CharSequence[] sequences = new CharSequence[size];
					String curIdc = mPlayer.getCurIdc();
					int itemindex = -1;
					for (int i = 0; i < size; i++) {
						sequences[i] = idcs.get(i).getName() + "(" + idcs.get(i).getDescription() + ")";
						if (idcs.get(i).getIdcId().equals(curIdc)) {
							itemindex = i;
						}
					}

					alert(sequences, itemindex, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							mPlayer.setIdcId(idcs.get(which).getCode(), null);
							dialog.dismiss();
						}
					});
				}
				break;
			case R.id.txtReword:
//			Reward r = new Reward();
//			r.setMoney(100);//100分
//			r.setComment("恭喜发财");
//			r.setDesc("你也要恭喜我发财");
//			mPlayer.reward(r);

//			流程mPlayer.reward -> 回调onGotoPay-调用支付宝支付-onRewardResult
				toast("开发者自行下载支付宝的sdk进行集成支付");
				break;
			case R.id.txtReName:
				final String action = getString(R.string.rename);
				final EditText et = new EditText(getActivity());
				new AlertDialog.Builder(getActivity()).setTitle(action).setView(et).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).setPositiveButton("修改", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String name = et.getText().toString().trim();
						UserInfo self = mPlayer.getSelfInfo();
						if (!StringUtil.isEmpty(name) && self != null && !name.equals(self.getName())) {
							mPlayer.reName(name, new OnTaskRet() {
								@Override
								public void onTaskRet(boolean b, int i, String s) {
									toast(action + (b ? "成功" : "失败"));
								}
							});
						} else {
							toast(action + "失败");
						}
					}
				}).create().show();
				break;
			case R.id.btnHongbao:
				if (hongbaoHolder != null) {
					hongbaoHolder.showSelfHongbaoList();
				}
				break;
			case R.id.btnMedalRank:
				//勋章列表获取,默认50条
				if (null != medalPraiseHolder) {
					medalPraiseHolder.getPraiseRecvList(IMedalPraise.TYPE_MEDAL);
				}
				break;
			case R.id.btnPraise://点赞
				if (null !=medalPraiseHolder ){
					medalPraiseHolder.clickPraise();
				}
				break;
		}
	}

	private void handDown() {
		txtHand.setText("举手");
		mPlayer.handUp(false, null);
		txtHand.setSelected(false);
	}

	public void onMicColesed() {
		txtMic.setVisibility(View.GONE);
	}

	public void onMicOpened(int inviteMediaType) {
		txtMic.setTag(inviteMediaType);
		txtMic.setVisibility(View.VISIBLE);
	}

	private void initRateSelectView() {
		List<String> list = new ArrayList<String>();
		list.add(getString(R.string.video_rate_nor));
		list.add(getString(R.string.video_rate_low));

		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				R.layout.spinner_layout, list);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerRate.setAdapter(adapter);
		spinnerRate.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
									   int arg2, long arg3) {
				if (mPlayer != null) {
					switch (arg2) {
						case 0:
							mPlayer.switchRate(VideoRate.RATE_NORMAL, null);
							break;
						case 1:
							mPlayer.switchRate(VideoRate.RATE_LOW, null);
							break;
					}
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	private void alert(CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener) {
		new AlertDialog.Builder(getActivity()).setSingleChoiceItems(items, checkedItem, listener).create().show();
	}

	public void onIdcList(List<PingEntity> arg0) {
		this.idcs = arg0;
	}

	private void toast(final String msg) {
		Activity a = getActivity();
		if (a != null) {
			a.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
				}
			});
		}

	}

	public void showHongbaoButton(final boolean enable) {
		isHongbaoEnable = enable;
		if (btnHongbao != null) {
			btnHongbao.post(new Runnable() {
				@Override
				public void run() {
					btnHongbao.setVisibility(enable ? View.VISIBLE : View.GONE);
				}
			});
		}
	}

	private void updateVolumeDisplay(int progress) {
		if (volumeTextView != null && getActivity() != null) {
			final String text = progress + "%";
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					volumeTextView.setText(text);
				}
			});
		}
	}


}