package com.baidu.rtc.sample;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

import com.baidu.rtc.BaiduRtcRoom;
import com.baidu.rtc.IRtcEventHandler;
import com.baidu.rtc.RTCVideoView;
import com.baidu.rtc.sample.data.RtcClientData;
import com.baidu.rtc.sample.splitscreen.DefaultFragment;
import com.baidu.rtc.sample.splitscreen.IRemoteVideoListener;
import com.webrtc.Logging;

import java.util.ArrayList;

/**
 * 多人模式视频通话
 */
public class RoomActivity extends FragmentActivity {
    private static final String TAG = "RoomActivity";
    private DefaultFragment mDefaultFragment;
    private ArrayList<IRemoteVideoListener> mIRemoteVideoListeners;
    private RtcRoomController mRtcController;
    private BaiduRtcRoom mRtcVideoRoom;
    private RtcClientData mClientData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        window.requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_videoroom);

        mRtcController = new RtcRoomController();
        mRtcController.onCreate(this,  getIntent(), mRoomCallback);
        // 初始化RTCRoom
        mRtcVideoRoom = mRtcController.initBdRtcRoom();
        mClientData = mRtcController.getClientData();
        // 初始化View
        initAllViews();
        // 登录房间
        mRtcController.loginBdRtcRoom();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /** 清除禁止熄屏 */
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        if (mRtcController != null) {
            mRtcController.onDestroy();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        mRtcController.onResume();
    }

    protected void initAllViews() {
        mDefaultFragment = new DefaultFragment();
        mDefaultFragment.setVideoRoom(mRtcVideoRoom);
        mDefaultFragment.setClientData(mClientData);
        addRemoteVideoListener((DefaultFragment) mDefaultFragment);
        navigateToFragment();
        ((TextView) findViewById(R.id.tv_room_name)).setText(String.format("房间名：%s", mClientData.mRoomName));
    }

    public void addRemoteVideoListener(IRemoteVideoListener listener) {
        if (mIRemoteVideoListeners == null) {
            mIRemoteVideoListeners = new ArrayList<>();
        }
        if (!mIRemoteVideoListeners.contains(listener)) {
            mIRemoteVideoListeners.add(listener);
        }
    }


    /**
     * 点击是否关闭本地视频
     *
     * @param view
     */
    public void onLocalVideoMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.setImageResource(R.drawable.btn_voice);
        } else {
            iv.setSelected(true);
            iv.setImageResource(R.drawable.btn_voice_selected);
        }
        mRtcVideoRoom.muteCamera(iv.isSelected());

        RTCVideoView rtcVideoView = getLocalVideoView();
        if (rtcVideoView != null) {
            rtcVideoView.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * 点击Mic 图标，是否停止采集音频
     *
     * @param view
     */
    public void onLocalAudioMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.setImageResource(R.drawable.btn_mute);
            mRtcVideoRoom.enableMicCapture(true);
        } else {
            iv.setSelected(true);
            iv.setImageResource(R.drawable.btn_mute_selected);
            mRtcVideoRoom.enableMicCapture(false);
        }
    }

    /**
     * 点击切换摄像头
     *
     * @param view
     */
    public void onSwitchCameraClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.setImageResource(R.drawable.btn_switch_camera);
        } else {
            iv.setSelected(true);
            iv.setImageResource(R.drawable.btn_switch_camera_selected);
        }
        mRtcVideoRoom.switchCamera();
    }

    /**
     * 点击切换扬声器
     *
     * @param view
     */
    public void onSpeakerClicked(View view) {
        if (mRtcVideoRoom == null) {
            return;
        }
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.setImageResource(R.drawable.btn_speaker);
            mRtcVideoRoom.setEnableSpeakerphone(false);
            Log.i(TAG, "onSpeakerClicked true");
        } else {
            iv.setSelected(true);
            iv.setImageResource(R.drawable.btn_speaker_selected);
            mRtcVideoRoom.setEnableSpeakerphone(true);
            Log.i(TAG, "onSpeakerClicked false");
        }
    }

    /**
     * 点击结束通话
     *
     * @param view
     */
    public void onEndCallClicked(View view) {
        super.finish();
    }

    public RTCVideoView getLocalVideoView() {
        return mDefaultFragment.getLocalView();
    }

    private void navigateToFragment() {
        if (!mDefaultFragment.isAdded()) {
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(R.id.right_layout, mDefaultFragment);
            transaction.commit();
        }
    }

    private IRtcEventHandler mRoomCallback = new IRtcEventHandler() {
        @Override
        public void onLoginSuccess(long roomId, long uid, int elapsed) {
            super.onLoginSuccess(roomId, uid, elapsed);
        }

        public void onRemoteUserJoinRoom(long uid, String name) {
            Logging.d(TAG, "onRemoteUserJoinRoom uid:" + uid + ",name:" + name);
            if (mIRemoteVideoListeners == null) {
                return;
            }
            for (int i = 0; i < mIRemoteVideoListeners.size(); i++) {
                mIRemoteVideoListeners.get(i).onRemoteUserJoin(uid, name);
            }
        }

        @Override
        public void onRemoteUserLeaveRoom(long uid, String name) {
            Logging.d(TAG, "onRemoteUserLeaveRoom uid:" + uid + ",name:" + name);
            if (mIRemoteVideoListeners == null) {
                return;
            }
            for (int i = 0; i < mIRemoteVideoListeners.size(); i++) {
                mIRemoteVideoListeners.get(i).onRemoteUserLeave(uid, name);
            }
        }
    };

}