package com.xunao.effectdemo.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.xunao.effectdemo.adapter.DeviceAdapter;
import com.xunao.effectdemo.dlan.DLNAControlCenter;
import com.xunao.effectdemo.dlan.IUIUpdateListener;
import com.hpplay.sdk.source.api.INewPlayerListener;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.hpplay.sdk.source.bean.CastBean;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.hpplay.sdk.source.easycast.IEasyCastListener;
import com.hpplay.sdk.source.easycast.bean.EasyCastBean;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.xunao.effectdemo.R;
import com.xunao.effectdemo.utils.SoundPoolUtil;

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

/**
 * author : 程中强
 * e-mail : 740479946@qq.com
 * date : 2022/9/1616:21
 * desc :
 * version: 1.0
 */
public class VideoPreviewPlay extends StandardGSYVideoPlayer {

	private boolean isFinish = false;
	private SoundPoolUtil soundPoolUtil;

	private ViewGroup mBrowseContainer;//投屏搜索列表
	private Button btn_cast;//投屏按钮
	private RelativeLayout rl_dlan_control;//投屏控制层
	private ImageView dlan_start;//投屏的播放暂停
	private TextView dlan_current,dlan_total;//投屏的时长
	private SeekBar dlan_progress;//投屏进度条
	private boolean isDlanPlay = false;
	public List<LelinkServiceInfo> mDevices = new ArrayList<>();
	public LelinkServiceInfo curTPDevice;

	private DeviceAdapter mDeviceAdapter;
	private ListView rvList;
	private IUIUpdateListener mUIListener;
	private INewPlayerListener mPushListener;
	private IEasyCastListener mCastListener;

	public void setIsFinish(boolean isFinish){
		this.isFinish = isFinish;
	}
	public VideoPreviewPlay(Context context, Boolean fullFlag) {
		super(context, fullFlag);
	}

	public VideoPreviewPlay(Context context) {
		super(context);
	}

	public VideoPreviewPlay(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public int getLayoutId() {
		return R.layout.activity_my_video;
	}

	public void stopDlan(){
		LelinkSourceSDK.getInstance().stopPlay();
	}

	private Handler handler = new Handler(){
		@Override
		public void handleMessage(@NonNull Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case 1001:
					Log.e("MyTag","结果收到消息");
//					if (mDeviceAdapter != null) {
						mDeviceAdapter.notifyDataSetChanged();
					rvList.setAdapter(mDeviceAdapter);
//					}
					break;
			}
		}
	};

	@Override
	protected void init(Context context) {
		super.init(context);

		soundPoolUtil= SoundPoolUtil.getInstance(context);
		mProgressBar = findViewById(R.id.progress);
		dlan_progress = findViewById(R.id.dlan_progress);
		mBrowseContainer = findViewById(R.id.mBrowseContainer);
		btn_cast = findViewById(R.id.btn_cast);
		rl_dlan_control = findViewById(R.id.rl_dlan_control);
		dlan_start = findViewById(R.id.dlan_start);
		dlan_current = findViewById(R.id.dlan_current);
		dlan_total = findViewById(R.id.dlan_total);

		rvList = findViewById(R.id.rv_device);
//		rvList.setLayoutManager(new LinearLayoutManager(context));
		mDevices = new ArrayList<>();
//		mDevices.clear();
		mDeviceAdapter = new DeviceAdapter(context, mDevices);
		rvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				curTPDevice = mDevices.get(i);

				DLNAControlCenter.getInstance().dlnaPlay(curTPDevice, mOriginUrl, "",0);

//			new Handler().postDelayed(new Runnable() {
//				@Override
//				public void run() {
//					DLNAControlCenter.getInstance().dlnaSeekToPlayPosition(curTPDevice, (int) (ijkVrVideoView.getCurrentPosition() / 1000.0f));
//				}
//			}, 3000);
			}
		});

		dlan_start.setOnClickListener(v->{

			if (isDlanPlay) {
				dlan_start.setImageResource(R.drawable.video_play_normal);
				LelinkSourceSDK.getInstance().pause();
			} else {
				dlan_start.setImageResource(R.drawable.video_pause_normal);
				LelinkSourceSDK.getInstance().resume();
			}
		});

		btn_cast.setOnClickListener(v->{
			LelinkSourceSDK.getInstance().setEasyCastListener(mCastListener);
			LelinkSourceSDK.getInstance().easyPush(mBrowseContainer);
//			LelinkSourceSDK.getInstance().setNewPlayListener(mPushListener);
//			mDevices.clear();
			onVideoPause();
			mBrowseContainer.setVisibility(VISIBLE);
//			DLNAControlCenter.getInstance().startLelinkSearch();
		});
		dlan_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				Log.e("MyTag","拖动:"+seekBar.getProgress()*getDuration()/100/1000);
				LelinkSourceSDK.getInstance().seekTo(seekBar.getProgress()*getDuration()/100/1000);
			}
		});


		mProgressBar.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				if(isFinish){
					soundPoolUtil.playSoundWithRedId(R.raw.buyao);
					Toast toast = Toast.makeText(context,"触摸事件",Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP,0,0);
					toast.show();
					return true;
				}
				return false;
			}
		});




		initCast();
	}

	void initCast(){
		mUIListener = new IUIUpdateListener() {
			@Override
			public void onUpdateDevices(List<LelinkServiceInfo> list) {
				for (LelinkServiceInfo lelinkServiceInfo : list) {
					if (mDevices.contains(lelinkServiceInfo)) {
						continue;
					} else {
						mDevices.add(lelinkServiceInfo);

						handler.sendEmptyMessage(1001);
					}
				}
			}

			@Override
			public void onConnect(LelinkServiceInfo info) {
//			lelinkCastSuccess(true);
			}


			@Override
			public void onDisconnect(LelinkServiceInfo info) {
//			DLNAControlCenter.getInstance().uploadCastDataToPlatform(false, curTPDevice, titleId);
			}

			@Override
			public void onNetChanged() {
			}

			@Override
			public void onBindSuccess() {
			}
		};

		mPushListener = new INewPlayerListener() {

			/**
			 * @param bean 投屏信息
			 *  内容开始加载
			 */
			@Override
			public void onLoading(CastBean bean) {
				btn_cast.setVisibility(GONE);
				rl_dlan_control.setVisibility(VISIBLE);
				isDlanPlay = true;
				dlan_total.setText(mTotalTimeTextView.getText());
			}

			/**
			 * @param bean 投屏信息
			 *  开始播放
			 */
			@Override
			public void onStart(CastBean bean) {
				dlan_start.setImageResource(R.drawable.video_pause_normal);
				isDlanPlay = true;
			}
			/**
			 * @param bean 投屏信息
			 *  播放暂停
			 */
			@Override
			public void onPause(CastBean bean) {
				dlan_start.setImageResource(R.drawable.video_play_normal);
				isDlanPlay = false;
			}
			/**
			 * 播放完成
			 * @param bean 投屏信息
			 * @param type 播放类型
			 */
			@Override
			public void onCompletion(CastBean bean, int type) {
				btn_cast.setVisibility(VISIBLE);
				rl_dlan_control.setVisibility(GONE);
				isDlanPlay = false;
				onVideoResume();
//			LelinkSourceSDK.getInstance().disconnect(lelinkServiceInfo);
			}

			/**
			 * @param bean 投屏信息
			 *  播放停止 （主动停止或者电视端停止均会回调）
			 */
			@Override
			public void onStop(CastBean bean) {
				isDlanPlay = false;
				btn_cast.setVisibility(VISIBLE);
				rl_dlan_control.setVisibility(GONE);
				onVideoResume();
			}
			/**
			 * 该接口暂未有数据回调
			 */
			@Override
			public void onSeekComplete(CastBean bean, int position) {

			}

			/**
			 * info信息回调，播放信息和收端能力查询等回调接口
			 */
			@Override
			public void onInfo(CastBean bean, int what, int extra) {
			}

			/**
			 * （重载接口）
			 */
			@Override
			public void onInfo(CastBean bean, int what, String data) {

			}

			/**
			 * @param bean 投屏信息
			 * @param what 错误类型
			 * @param extra 额外错误码
			 */
			@Override
			public void onError(CastBean bean, int what, int extra) {
				String text = "未知异常";
				switch (extra) {
					case EXTRA_ERROR_AUTH:
					case EXTRA_ERROR_AUTH_TIME_DONE:
						text = "SDK认证失败";
						break;
					case EXTRA_NEED_SCREEN_CODE:
						text = "请输入密码";
//					getActivity().runOnUiThread(new Runnable() {
//						@Override
//						public void run() {
//							showPWDDialog();
//						}
//					});
						break;
					case EXTRA_DEVICE_OFFLINE:
						text = "接收端不在线";
						break;
					case EXTRA_ERROR_PUSH_IO:
						text = "网络通讯异常";
						break;
				}
				if (TextUtils.isEmpty(text)) {
					text = "推送 onError " + what + "/" + extra;
				}
			}

			/**
			 *
			 * 该接口暂未有数据回调
			 */
			@Override
			public void onVolumeChanged(CastBean bean, float percent) {

			}

			/**
			 * 进度更新回调
			 * @param bean 投屏信息
			 * @param duration 最大进度 （单位秒）
			 * @param position 当前进度 （单位秒）
			 */
			@Override
			public void onPositionUpdate(CastBean bean, long duration, long position) {
				if(duration!=0)
					dlan_progress.setProgress((int) (position*100/duration));
				dlan_current.setText(CommonUtil.stringForTime((int) position*1000));
			}
		};

//		DLNAControlCenter.getInstance().setUIListener(mUIListener);
//		CastManager.getInstance().addPlayerListener(mPushListener);

		mCastListener = new IEasyCastListener() {

			/**
			 * 如果没有触发此回调，则表示此次未搜索到设备或用户未投屏
			 * @param lelinkServiceInfo
			 * @return
			 */
			@Override
			public EasyCastBean onCast(LelinkServiceInfo lelinkServiceInfo) {
				EasyCastBean bean = new EasyCastBean();
				bean.url = mOriginUrl; //实际需要投屏的url
				return bean;
			}

			/**
			 * 如果投屏失败，在搜索页面关闭的时候，会触发回调
			 * @param lelinkServiceInfo
			 * @param easyCastBean
			 * @param what
			 * @param extra
			 */
			@Override
			public void onCastError(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean, int what, int extra) {
				Log.e("MyTag","推送失败"+what+"   "+extra);
				btn_cast.setVisibility(VISIBLE);
				mBrowseContainer.setVisibility(GONE);
				rl_dlan_control.setVisibility(GONE);
				isDlanPlay = false;
				onVideoResume();
			}

			/**
			 * 推送成功
			 * @param lelinkServiceInfo
			 * @param easyCastBean
			 */
			@Override
			public void onCastLoading(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
				Log.e("MyTag","推送成功");
				btn_cast.setVisibility(GONE);
				mBrowseContainer.setVisibility(GONE);
				rl_dlan_control.setVisibility(VISIBLE);
				isDlanPlay = true;
				dlan_total.setText(mTotalTimeTextView.getText());
			}

			/**
			 * 暂停
			 * @param lelinkServiceInfo
			 * @param easyCastBean
			 */
			@Override
			public void onCastPause(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
				dlan_start.setImageResource(R.drawable.video_play_normal);
				isDlanPlay = false;
			}

			/**
			 * 起播 或 收端暂停之后恢复播放
			 * @param lelinkServiceInfo
			 * @param easyCastBean
			 */
			@Override
			public void onCastStart(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
				dlan_start.setImageResource(R.drawable.video_pause_normal);
				isDlanPlay = true;
			}

			@Override
			public void onCastPositionUpdate(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean, long duration, long position) {
				Log.e("MyTag","当前:"+position);
				if(duration!=0)dlan_progress.setProgress((int) (position*100/duration));
				dlan_current.setText(CommonUtil.stringForTime((int) position*1000));
			}

			/**
			 * 收端播放结束，如果需要实现下一集，可在之后的onCast回调中提供播放信息
			 * @param lelinkServiceInfo
			 * @param easyCastBean
			 */
			@Override
			public void onCastCompletion(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
				btn_cast.setVisibility(VISIBLE);
				rl_dlan_control.setVisibility(GONE);
				mBrowseContainer.setVisibility(GONE);
				isDlanPlay = false;
				onVideoResume();
//				LelinkSourceSDK.getInstance().disconnect(lelinkServiceInfo);
			}

			/**
			 * 搜索退出播放，不同于 onCastCompletion，此时需要恢复APP视频播放
			 * @param lelinkServiceInfo
			 * @param easyCastBean
			 */
			@Override
			public void onCastStop(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
				isDlanPlay = false;
				btn_cast.setVisibility(VISIBLE);
				rl_dlan_control.setVisibility(GONE);
				mBrowseContainer.setVisibility(GONE);
				onVideoResume();
//				LelinkSourceSDK.getInstance().disconnect(lelinkServiceInfo);
			}

			@Override
			public void onDismiss() {
				btn_cast.setVisibility(VISIBLE);
				rl_dlan_control.setVisibility(GONE);
				mBrowseContainer.setVisibility(GONE);
				isDlanPlay = false;
				onVideoResume();
//			LelinkSourceSDK.getInstance().stopPlay();
			}
		};
	}






}
