package cn.tee3.demo.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.support.annotation.RequiresApi;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Random;

import cn.tee3.avd.AVDEngine;
import cn.tee3.avd.MUserManager;
import cn.tee3.avd.MVideo;
import cn.tee3.avd.Room;
import cn.tee3.avd.RoomInfo;
import cn.tee3.avd.Tlog;
import cn.tee3.avd.User;
import cn.tee3.manager.bean.CommonBean;
import cn.tee3.manager.service.EngineConfigure;
import cn.tee3.manager.service.MeetingManager;
import cn.tee3.manager.service.RequestPermissions;
import cn.tee3.manager.util.MyToast;
import cn.tee3.manager.service.AVDManager;
import cn.tee3.manager.service.RoomManager;
import cn.tee3.manager.util.StringUtils;
import cn.tee3.demo.R;
import tee3.webrtc.CameraVideoCapturer;

/**
 * 两种启动模式：
 *  1. 提前初始化好SDK引擎，MeetingActivity启动后加会和离开时做离会操作，JoinMeetActivity 关闭时再释放SDK；
 *  2. 在每次加会时都重新初始化SDK引擎和加入房间操作，在离会时做离会和SDK释放
 *
 * 注：使用第2种方式加会由于每次需要重新初始化SDK引擎，会带来一定的延时，尤其是第一次初始化SDK引擎耗时800ms~1s。
 */
public class JoinMeetActivity extends Activity {
    public static String TAG;
    private EditText etRoomId;
    private EditText etUserName;
    public static String ROOM_ID = "roomId";
    public static String USER_NAME = "userName";

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_meet);

        initView();
    }

    private void initView() {
        etRoomId = findViewById(R.id.etRoomId);
        etUserName = findViewById(R.id.etUserName);
        etUserName.setText(StringUtils.getDeviceBrand() + "-" + System.currentTimeMillis() % 1000);

        String roomId = "r" + System.currentTimeMillis() / 1000;  // 随机房间号，可根据自己需要配置为固定房间。

        etRoomId.setText(roomId);

        RequestPermissions.permissionHelper(this)
                .request(null, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 加入房间
     */
    public void onClickJoinRoom(View view) {
        String roomId = etRoomId.getText().toString();
        String userName = etUserName.getText().toString();
        String userId = userName;
        if (roomId.length() == 0) {
            Toast.makeText(this, "RoomId 为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!RequestPermissions.getInstance().isGranted(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Tlog.w("JoinMeetActivity", "没有写文件权限，日志文件将不能正常生成！");
        }

        final Intent intent = new Intent(JoinMeetActivity.this, WhiteboardActivity.class);
        intent.putExtra(JoinMeetActivity.ROOM_ID, roomId);
        intent.putExtra(JoinMeetActivity.USER_NAME, userName);

        if (MyApplication.SETUP_TYPE == MyApplication.SetupType.REJOIN_ROOM_MODE) {
            if (EngineConfigure.getInstance().isWorking()) {    /** 判断SDK引擎是否已初始化，未初始化则初始化 */
                startActivity(intent);
            } else {
                MyApplication.initAVDEngine(this, new AVDManager.InitAVDEngineListener() {
                    @Override
                    public void success() {
                        MyToast.showToast(JoinMeetActivity.this, "初始化引擎成功", true, true);
                        startActivity(intent);
                    }

                    @Override
                    public void error(String errorCode) {
                        MyToast.showToast(JoinMeetActivity.this, errorCode, true, true);
                    }
                });
            }
        } else {
            AVDManager.getInstance()
                    .init(this, new RoomManager.RoomParams(roomId, userName, userId), new AVDManager.AVDSetupListener() {   /** 初始化SDK引擎 并 加入房间 */
                        @Override
                        public void success() {
                            startActivity(intent);
                        }

                        @Override
                        public void error(String errorCode) {
                            MyToast.showToast(JoinMeetActivity.this, errorCode, true, true);
                        }
                    });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MyApplication.SETUP_TYPE == MyApplication.SetupType.REJOIN_ROOM_MODE) {
            AVDManager.getInstance().dispose(); /** SDK 释放 */
        }
        Process.killProcess(Process.myPid());
    }
}

