package com.gensee.fragement;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


import androidx.fragment.app.Fragment;

import com.gensee.config.ConfigApp;
import com.gensee.entity.BroadCastMsg;
import com.gensee.entity.InitParam;
import com.gensee.entity.LiveInfo;
import com.gensee.entity.PayInfo;
import com.gensee.entity.PingEntity;
import com.gensee.entity.RewardResult;
import com.gensee.extention.RoomDataEvent;
import com.gensee.media.IVideoIndication;
import com.gensee.net.AbsRtAction;
import com.gensee.player.OnPlayListener;
import com.gensee.player.Player;
import com.gensee.playerdemo.PlayerDemoActivityEx;
import com.gensee.playerdemo.R;
import com.gensee.routine.UserInfo;
import com.gensee.utils.GenseeLog;
import com.gensee.view.GSGPUVideoView;
import com.gensee.view.GSVideoView;
import com.gensee.view.ILocalVideoView;
import com.gensee.view.beauty.GSLocalVideoView;

import java.util.List;


public class SimpleLiveFragment extends Fragment implements RoomDataEvent.Callback, OnPlayListener {
    private static final String TAG = "SimpleLiveFragment";

    private InitParam mInitParam;
    private boolean bJoinSuccess = false;
    private Player mPlayer;
    private GSGPUVideoView videoView;

    @SuppressLint("ValidFragment")
    public SimpleLiveFragment(InitParam initParam) {
        mInitParam = initParam;
    }
    public SimpleLiveFragment() {

    }



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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_simple_live, container, false);
    }

    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        videoView = (GSGPUVideoView) view.findViewById(R.id.videoview);

        mPlayer = new Player();
        mPlayer.setGSVideoView((IVideoIndication) videoView);
        mPlayer.registerExtension(new RoomDataEvent(this));

        join();

    }

    private void join() {
        joinLive(mInitParam);
    }

    public void joinLive(InitParam p) {
        if (p == null) {
            return;
        }
        if (!bJoinSuccess) {
//			mProgressBar.setVisibility(View.VISIBLE);
            toastMsg( "正在玩命加入...");
            mPlayer.join(getContext(), p, this);
//			finish();
        } else {
//            dialogLeave();
        }
    }


    @Override
    public void onRoomData(String key, String value) {
        GenseeLog.d(TAG,"onRoomData key = " + key + " value = " + value);
        if (SCREEN_LOCK.equals(key)){
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    toastMsg("1".equals(value)?"老师已开启锁屏功能":"老师已关闭锁屏功能");
                }
            },2000);
        }
    }

    private void toastMsg(final String msg) {
        if (msg != null) {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(getActivity(), msg,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onJoin(int result) {
        String msg = null;
        switch (result) {
            case JOIN_OK:

                msg = "加入成功";
                mHandler.sendEmptyMessage(PlayerDemoActivityEx.HANDlER.SUCCESSJOIN);
                break;
            case JOIN_CONNECTING:
                msg = "正在加入";
                break;
            case JOIN_CONNECT_FAILED:
                msg = "连接失败";
                break;
            case JOIN_RTMP_FAILED:
                msg = "连接服务器失败";
                break;
            case JOIN_TOO_EARLY:
                msg = "直播还未开始";
                break;
            case JOIN_LICENSE:
                msg = "人数已满";
                break;
            default:
                msg = "加入返回错误" + result;
                break;
        }
        toastMsg(msg);
    }

    @Override
    public void onUserJoin(UserInfo userInfo) {

    }

    @Override
    public void onUserLeave(UserInfo userInfo) {

    }

    @Override
    public void onUserUpdate(UserInfo userInfo) {

    }

    @Override
    public void onRosterTotal(int i) {

    }

    @Override
    public void onReconnecting() {
        GenseeLog.d(TAG, "onReconnecting");
        //断线重连
        mHandler.sendEmptyMessage(PlayerDemoActivityEx.HANDlER.RECONNECTING);
    }

    @Override
    public void onLeave(int reason) {
        String msg = null;
        switch (reason) {
            case LEAVE_NORMAL:
                msg = "您已经退出直播间";
                break;
            case LEAVE_KICKOUT:
                msg = "您已被踢出直播间";
                mHandler.sendEmptyMessage(PlayerDemoActivityEx.HANDlER.SUCCESSLEAVE);
                break;
            case LEAVE_TIMEOUT:
                msg = "连接超时，您已经退出直播间";
                break;
            case LEAVE_CLOSE:
                msg = "直播已经停止";
                break;
            case LEAVE_UNKNOWN:
                msg = "您已退出直播间，请检查网络、直播间等状态";
                break;
            case LEAVE_RELOGIN:
                msg = "被踢出直播间（相同用户在其他设备上加入）";
                break;
            default:
                break;
        }
        if (null != msg) {
            toastMsg(msg);
        }
    }

    @Override
    public void onCaching(boolean isCaching) {
        GenseeLog.d(TAG, "onCaching isCaching = " + isCaching);
    }

    @Override
    public void onErr(int errCode) {
        GenseeLog.i(TAG, "onErr code = " + errCode);
        String msg = null;
        switch (errCode) {
            case AbsRtAction.ErrCode.ERR_DOMAIN:
                msg = "域名domain不正确";
                break;
            case AbsRtAction.ErrCode.ERR_TIME_OUT:
                msg = "请求超时，稍后重试";
                break;
            case AbsRtAction.ErrCode.ERR_SITE_UNUSED:
                msg = "站点不可用，请联系客服或相关人员";
                break;
            case AbsRtAction.ErrCode.ERR_UN_NET:
                msg = "网络不可用，请检查网络连接正常后再试";
                break;
            case AbsRtAction.ErrCode.ERR_SERVICE:
                msg = "service  错误，请确认是webcast还是training";
                break;
            case AbsRtAction.ErrCode.ERR_PARAM:
                msg = "initparam参数不全";
                break;
            case AbsRtAction.ErrCode.ERR_THIRD_CERTIFICATION_AUTHORITY:
                msg = "第三方认证失败";
                break;
            case AbsRtAction.ErrCode.ERR_NUMBER_UNEXIST:
                msg = "编号不存在";
                break;
            case AbsRtAction.ErrCode.ERR_TOKEN:
                msg = "口令错误";
                break;
            case AbsRtAction.ErrCode.ERR_LOGIN:
                msg = "站点登录帐号或登录密码错误";
                break;
            default:
                msg = "错误：errCode = " + errCode;
                break;
        }
        if (msg != null) {
            toastMsg(msg);
        }
    }

    @Override
    public void onDocSwitch(int i, String s) {

    }

    @Override
    public void onVideoBegin() {

    }

    @Override
    public void onVideoEnd() {

    }

    @Override
    public void onVideoSize(int i, int i1, boolean b) {

    }

    @Override
    public void onAudioLevel(int i) {

    }

    @Override
    public void onPublish(boolean b) {

    }

    @Override
    public void onSubject(String subject) {
        GenseeLog.d(TAG, "onSubject subject = " + subject);
    }

    @Override
    public void onPageSize(int i, int i1, int i2) {

    }

    @Override
    public void onVideoDataNotify() {

    }

    @Override
    public void onPublicMsg(BroadCastMsg broadCastMsg) {

    }

    @Override
    public void onLiveText(String s, String s1) {

    }

    @Override
    public void onRollcall(int i) {

    }

    @Override
    public void onLottery(int i, String s) {

    }

    @Override
    public void onFileShare(int i, String s, String s1) {

    }

    @Override
    public void onFileShareDl(int i, String s, String s1) {

    }

    @Override
    public void onInvite(int i, boolean b) {

    }

    @Override
    public void onMicNotify(int i) {

    }

    @Override
    public void onCameraNotify(int i) {

    }

    @Override
    public void onScreenStatus(boolean b) {

    }

    @Override
    public void onModuleFocus(int i) {

    }

    @Override
    public void onIdcList(List<PingEntity> list) {

    }

    @Override
    public void onThirdVote(String s) {

    }

    @Override
    public void onRewordEnable(boolean b, boolean b1) {

    }

    @Override
    public void onRedBagTip(RewardResult rewardResult) {

    }

    @Override
    public void onGotoPay(PayInfo payInfo) {

    }

    @Override
    public void onGetUserInfo(UserInfo[] userInfos) {

    }

    @Override
    public void onLiveInfo(LiveInfo liveInfo) {

    }

    @Override
    public void onHongbaoEnable(boolean b) {

    }

    @Override
    public void onDoubleTeacherStatusChange(int i) {

    }


    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PlayerDemoActivityEx.HANDlER.USERDECREASE:

                    break;
                case PlayerDemoActivityEx.HANDlER.USERINCREASE:
                case PlayerDemoActivityEx.HANDlER.USERUPDATE:

                    break;
                case PlayerDemoActivityEx.HANDlER.SUCCESSJOIN:

                    bJoinSuccess = true;

                    break;
                case PlayerDemoActivityEx.HANDlER.SUCCESSLEAVE:

                    break;
                case PlayerDemoActivityEx.HANDlER.CACHING:
                    toastMsg( "正在缓冲...");

                    break;
                case PlayerDemoActivityEx.HANDlER.CACHING_END:

                    break;
                case PlayerDemoActivityEx.HANDlER.RECONNECTING:
                    toastMsg( "正在重连...");
                    break;
                default:
                    break;
            }
        }
    };

    private void releasePlayer() {
        if (null != mPlayer && bJoinSuccess) {
            mPlayer.leave();
            bJoinSuccess = false;
        }
//        mPlayer.release();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        releasePlayer();
    }
}