package cn.tee3.demo.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.AudioRouting;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.tee3.avd.AVDEngine;
import cn.tee3.avd.AudioRoute;
import cn.tee3.avd.Device;
import cn.tee3.avd.MAudio;
import cn.tee3.avd.MScreen;
import cn.tee3.avd.MUserManager;
import cn.tee3.avd.MVideo;
import cn.tee3.avd.MWhiteboard;
import cn.tee3.avd.Room;
import cn.tee3.avd.RoomInfo;
import cn.tee3.avd.User;
import cn.tee3.avd.WhiteboardView;
import cn.tee3.demo.R;
import cn.tee3.demo.View.UserRecyclerViewAdapter;
import cn.tee3.demo.View.VideoFragment;
import cn.tee3.demo.View.VideoPagerAdapter;
import cn.tee3.manager.service.AVDManager;
import cn.tee3.manager.service.MeetingManager;
import cn.tee3.manager.service.RequestPermissions;
import cn.tee3.manager.service.RoomManager;
import cn.tee3.manager.util.MyToast;
import cn.tee3.manager.view.T3VideoView;
import tee3.webrtc.Camera2Session;
import tee3.webrtc.RendererCommon;
import tee3.webrtc.ScreenCapturerAndroid;

/**
 * 白板示例代码
 */
public class WhiteboardActivity extends AppCompatActivity implements View.OnClickListener, VideoFragment.OnFragmentCreateViewListener {

    private LinearLayout llCamera;
    private LinearLayout llMicrophone;
    private LinearLayout llSwitch;
    private LinearLayout llUsers;
    private LinearLayout llUsersList;
    private LinearLayout llWhiteboard;
    private RecyclerView recyclerView;
    private WhiteboardView whiteboardView;
    private MWhiteboard mWhiteboard;

    private ViewPager viewPager;
    private UserRecyclerViewAdapter adapter;

    private ImageView ivCamera;
    private ImageView ivMicrophone;

    private List<VideoFragment> fragmentList = new ArrayList<>();
    private List<T3VideoView> videoViewList = new ArrayList<>();

    private MediaProjectionManager mediaProjectionManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_whiteboard);

        initView();

        if (MyApplication.SETUP_TYPE == MyApplication.SetupType.REJOIN_ROOM_MODE) {
            Intent intent = getIntent();
            String roomId = intent.getStringExtra(JoinMeetActivity.ROOM_ID);
            String userName = intent.getStringExtra(JoinMeetActivity.USER_NAME);

            AVDManager.getInstance()
                    .init(this, new RoomManager.RoomParams(roomId, userName, userName), new AVDManager.AVDSetupListener() {
                        /** 加入房间 */
                        @Override
                        public void success() {
                            initWhiteboard();
                            initFragment(); /** 更新页面 视频渲染 */
                        }

                        @Override
                        public void error(String errorCode) {
                            MyToast.showToast(WhiteboardActivity.this, errorCode, true, true);
                        }
                    });
        } else {
            initWhiteboard();
            initFragment();
        }
    }

    private void initView() {
        llCamera = findViewById(R.id.ll_camera);
        llMicrophone = findViewById(R.id.ll_microphone);
        llSwitch = findViewById(R.id.ll_switch);
        llUsers = findViewById(R.id.ll_users);
        llUsersList = findViewById(R.id.ll_usersList);
        llWhiteboard = findViewById(R.id.ll_whiteboard);
        viewPager = findViewById(R.id.viewpager);
        ivCamera = findViewById(R.id.iv_camera);
        ivMicrophone = findViewById(R.id.iv_microphone);
        recyclerView = findViewById(R.id.recyclerView_users);
        llCamera.setOnClickListener(this);
        llMicrophone.setOnClickListener(this);
        llSwitch.setOnClickListener(this);
        llUsers.setOnClickListener(this);
        llWhiteboard.setOnClickListener(this);
    }

    /**
     * 初始化白板
     */
    private void initWhiteboard() {
        whiteboardView = findViewById(R.id.whiteboardView);
        whiteboardView.setWhiteboardColor(Color.WHITE);   // 设置白板背景色
        whiteboardView.setBackgroundColor(Color.BLACK);   // 设置画布背景色，默认为透明色时如果白板处于布局的顶层底层布局将不会被遮盖
        mWhiteboard = MWhiteboard.getWhiteboard(RoomManager.getInstance().getRoom());
        mWhiteboard.showToolbar(true)
                .onAttachView(whiteboardView)
                .setListener(new MWhiteboard.Listener() {
                    @Override
                    public void onCreateBoardNotify(MWhiteboard.Whiteboard board) {
                    }

                    @Override
                    public void onRemoveBoardNotify(String bid) {
                    }

                    @Override
                    public void onUpdateBoardNotify(MWhiteboard.Whiteboard board) {

                    }

                    @Override
                    /** 共享白板(包含自己) */
                    public void onShareBoardNotify(MWhiteboard.Whiteboard board) {
                    }

                    @Override
                    /** 关闭白板(包含自己) */
                    public void onCloseBoardNotify(String bid) {
                    }
                });
    }

    /**
     * 初始化视频渲染窗口，待窗口初始化完成后再启动视频渲染
     */
    private void initFragment() {
        fragmentList.add(VideoFragment.build());
        fragmentList.add(VideoFragment.build());
        fragmentList.get(0).addOnCreateViewListener(this);
        fragmentList.get(1).addOnCreateViewListener(this);
        VideoPagerAdapter videoPagerAdapter = new VideoPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(videoPagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                fragmentList.get(i).setCurrentPage(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private void showHideUserList() {
        if (llUsersList.getVisibility() == View.VISIBLE) {
            llUsersList.setVisibility(View.GONE);
        } else {
            llUsersList.setVisibility(View.VISIBLE);
            if (adapter == null) {
                recyclerView.setHasFixedSize(true);
                LinearLayoutManager layoutManager = new LinearLayoutManager(this);
                recyclerView.setLayoutManager(layoutManager);
                adapter = new UserRecyclerViewAdapter(this, MeetingManager.getInstance().getMeetingUsers());
                recyclerView.setAdapter(adapter);
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (llUsersList.getVisibility() == View.VISIBLE) {
                        adapter.updateUserList(MeetingManager.getInstance().getMeetingUsers());
                        new Handler().postDelayed(this, 500);
                    }
                }
            }, 1000);
        }
    }

    @Override
    public void onFragmentCreateView(List<T3VideoView> videoList, VideoFragment videoFragment) {
        if (fragmentList.get(0).hashCode() == videoFragment.hashCode()) {
            videoViewList.addAll(0, videoList);
        } else {
            videoViewList.addAll(videoList);
        }

        if (videoViewList.size() >= fragmentList.size() * VideoFragment.VIDEO_VIEW_COUNT) {
            for (T3VideoView videoView : videoViewList) {
                videoView.setImageResource(R.drawable.img_novideo_bg);
                videoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
            }

            videoViewList.get(0).addFirstFrameComingListener(new T3VideoView.FirstFrameComingListener() {
                @Override
                public void onFirstFrameComingListener() {
                    long curTime = System.currentTimeMillis();
                }
            });
            AudioRoute.instance().setAudioMode(AudioManager.MODE_NORMAL);

            /** 界面初始化完成后执行 “视频渲染” */
            AVDManager.getInstance()
                    // 设置视频容器列表
                    .setVideoRenders(videoViewList)
                    // 设置摄像头开关回调
                    .setCameraCallback(new MeetingManager.CameraCallback() {
                        @Override
                        public void success(boolean isOpen) {
                            ivCamera.setImageResource(isOpen ? R.drawable.img_open_camera : R.drawable.img_close_camera); // 更新摄像头图标
                        }

                        @Override
                        public void error(int errorCode) {
                            MyToast.showToast(WhiteboardActivity.this, "开关摄像头失败：" + errorCode, true);
                        }
                    })
                    // 设置麦克风开关回调
                    .setMicrophoneCallback(new MeetingManager.MicrophoneCallback() {
                        @Override
                        public void success(boolean isOpen) {
                            ivMicrophone.setImageResource(isOpen ? R.drawable.img_open_microphone : R.drawable.img_close_microphone); // 更新麦克风图标
                        }

                        @Override
                        public void error(int errorCode) {
                            MyToast.showToast(WhiteboardActivity.this, "开关麦克风失败：" + errorCode, true);
                        }
                    })
                    // 屏幕保持常亮
                    .keepScreenOn(WhiteboardActivity.this)
                    .enableCamera2API(true)
                    // 设置码流
                    .setVideoBitrateWithBps(1800 * 1000, 2000 * 1000)
                    // 启动音视频处理（自动模式）
                    .setup4Auto(this, new MeetingManager.SetupCallback() {
                        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void success(String code) {

                            /** 获取SD卡读写权限，否则不能生成日志文件 */
                            RequestPermissions.permissionHelper(WhiteboardActivity.this)
                                    .request(null,
                                            Manifest.permission.READ_PHONE_STATE,
                                            Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.CAMERA,
                                            Manifest.permission.RECORD_AUDIO);
                        }

                        @Override
                        public void error(String code) {
                        }
                    });
        }
    }

    /**
     * 共享本地屏幕
     */
    @TargetApi(21)
    private void startScreenCapture() {
        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), 1);
    }

    @TargetApi(21)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            MyToast.showToast(this, "共享屏幕权限未通过", false);
            return;
        }
        MeetingManager.getInstance().getMVideo().sendScreenIntent(data);

        /** 1. 共享全屏 */
        MeetingManager.getInstance().getScreen().publishedScreens(MScreen.ScreenResolution.SCREEN_720P, 20, true);

        /** 2. 共享屏幕的指定区域 */
//        ScaleScreenCapturer.ScaleZone scaleZone = new ScaleScreenCapturer.ScaleZone(0,    // 起始x坐标
//                                                                                    0,     // 起始y坐标
//                                                                                    1372,    // 截图区域宽度
//                                                                                    1008); // 截图区域高度
//        MeetingManager.getInstance().getScreen().publishedScreens(MScreen.ScreenResolution.SCREEN_1080P, 20, false);
//        MeetingManager.getInstance().getScreen().publishScaleScreen(scaleZone);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_camera:        // 开关摄像头
                MeetingManager.getInstance().openCloseCamera(this);
                break;
            case R.id.ll_microphone:    // 开关麦克风
                MeetingManager.getInstance().openCloseMicrophone(this);
                break;
            case R.id.ll_switch:        // 前后摄像头切换
                MeetingManager.getInstance().frontBackCameraSwitch();
                break;
            case R.id.ll_users:        // 查看用户列表
                showHideUserList();
                break;
            case R.id.ll_whiteboard:   // 共享、停止白板
                if (mWhiteboard.hasLocalWhiteboardShared()) {
                    mWhiteboard.closeLocalBoard();  // 关闭白板
                } else {
                    mWhiteboard.createLocalWhiteboard("test", "test", Color.WHITE);  // 创建白板，这里设置发布出去的白板颜色为白色
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (llUsersList.getVisibility() == View.VISIBLE) {
            llUsersList.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MyApplication.SETUP_TYPE == MyApplication.SetupType.REJOIN_ROOM_MODE) {
            AVDManager.getInstance().releaseRoom(); /** 离开房间并清理现场 */
        } else {
            AVDManager.getInstance().dispose();     /** 离开房间、SDK释放并清理现场 */
        }
    }

    boolean isShared;
    public void shareScreen(View view) {
        if (isShared) {
            MeetingManager.getInstance().getScreen().unpublishedScreens();
            ((Button) view).setText("开启共享屏幕");
        } else {
            startScreenCapture();
            ((Button) view).setText("停止共享屏幕");
        }
        isShared = !isShared;
    }
}
