package com.rv.im.call;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.rv.im.R;
import com.rv.im.call.event.MessageEventCancelOrHangUp;
import com.rv.im.call.event.MessageHangUpPhone;
import com.rv.im.enums.CallTypeEnum;
import com.rv.im.util.DialogHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jitsi.meet.sdk.JitsiMeetView;
import org.jitsi.meet.sdk.JitsiMeetViewListener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 2018-2-27 录屏，保存至本地视频
 */
public class Jitsi_connecting_second extends AppCompatActivity {
    private static final String TAG = "jitsi";
    // 屏幕录制
    private static final int RECORD_REQUEST_CODE = 0x01;
    // 计时，给悬浮窗调用
    public static String time = null;
    private String mLocalHost = "https://meet.dfangche.com/";  // 本地地址,现改为变量
    // 通话类型(单人语音、单人视频、群组语音、群组视频)
    private int mCallType;
    private String fromUserId;
    private String toUserId;

    private long startTime = System.currentTimeMillis();// 通话开始时间
    private long stopTime; // 通话结束时间
    private FrameLayout mFrameLayout;
    private JitsiMeetView mJitsiMeetView;

    // 当用户手动锁屏时，结束当前通话
    private ScreenListener mScreenListener;
    private RecordService recordService;
//    private ServiceConnection connection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName className, IBinder service) {
//            DisplayMetrics metrics = new DisplayMetrics();
//            getWindowManager().getDefaultDisplay().getMetrics(metrics);
//            RecordService.RecordBinder binder = (RecordService.RecordBinder) service;
//            recordService = binder.getRecordService();
//            recordService.setConfig(metrics.widthPixels, metrics.heightPixels, metrics.densityDpi);
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName arg0) {
//        }
//    };
    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("mm:ss");
    CountDownTimer mCountDownTimer = new CountDownTimer(18000000, 1000) {// 开始计时，用于显示在悬浮窗上，且每隔一秒发送一个广播更新悬浮窗
        @Override
        public void onTick(long millisUntilFinished) {
            time = formatTime();
            Jitsi_connecting_second.this.sendBroadcast(new Intent(CallConstants.REFRESH_FLOATING));
        }

        @Override
        public void onFinish() {// 12小时进入Finish

        }
    };

    public static void start(Context ctx, String room, boolean isVideo) {
        Intent intent = new Intent(ctx, Jitsi_connecting_second.class);
        if (isVideo) {
            intent.putExtra("type", 2);
        } else {
            intent.putExtra("type", 1);
        }
        intent.putExtra("fromuserid", room);
        intent.putExtra("touserid", room);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 自动解锁屏幕 | 锁屏也可显示 | Activity启动时点亮屏幕 | 保持屏幕常亮
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.jitsiconnecting);
        initData();
        initView();
        initEvent();
        EventBus.getDefault().register(this);
    }

//    @Override
//    public void onCoreReady() {
//        super.onCoreReady();
//        sendCallingMessage();// 对方可能一进入就已经挂掉了，我们就会误判对方未老版本，所以一进入就发送一条 "通话中" 消息给对方
//    }

    private void initData() {
        mCallType = getIntent().getIntExtra("type", 0);
        fromUserId = getIntent().getStringExtra("fromuserid");
        toUserId = getIntent().getStringExtra("touserid");

        JitsistateMachine.isInCalling = true;
        JitsistateMachine.callingOpposite = toUserId;

//        if (mCallType == 1 || mCallType == 2) {// 集群
//            mLocalHost = getIntent().getStringExtra("meetUrl");
//            if (TextUtils.isEmpty(mLocalHost)) {
////                mLocalHost = coreManager.getConfig().JitsiServer;
//            }
//        } else {
////            mLocalHost = coreManager.getConfig().JitsiServer;
//        }

        if (TextUtils.isEmpty(mLocalHost)) {
            Toast.makeText(this, getString(R.string.tip_meet_server_empty), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * startWithAudioMuted:是否禁用语音
     * startWithVideoMuted:是否禁用录像
     */
    private void initView() {
        mFrameLayout = findViewById(R.id.jitsi_view);
        mJitsiMeetView = new JitsiMeetView(this);
        mFrameLayout.addView(mJitsiMeetView);

        // 配置房间参数
        Bundle urlObject = new Bundle();
        Bundle config = new Bundle();
        if (mCallType == 1 || mCallType == 3) {
            config.putBoolean("startWithAudioMuted", false);
            config.putBoolean("startWithVideoMuted", true);
        } else if (mCallType == 2 || mCallType == 4) {
            config.putBoolean("startWithAudioMuted", false);
            config.putBoolean("startWithVideoMuted", false);
        }
        urlObject.putBundle("config", config);
        if (mCallType == 3) {// 群组语音添加标识，防止和群组视频进入同一房间地址
            urlObject.putString("url", mLocalHost + "/audio" + fromUserId);
        } else {
            urlObject.putString("url", mLocalHost + fromUserId);
        }
//        mJitsiMeetView.setAvatarURL(AvatarHelper.getAvatarUrl(coreManager.getSelf().getUserId(), false));
        // 开始加载
        mJitsiMeetView.loadURLObject(urlObject);
    }

    private void initEvent() {

        mJitsiMeetView.setListener(new JitsiMeetViewListener() {

            @Override
            public void onLoadConfigError(Map<String, Object> map) { // 加载配置时错误
                Log.e("jitsi", "1");
            }

            @Override
            public void onConferenceFailed(Map<String, Object> map) {// 会议失败
                Log.e(TAG, "2");
                finish();
            }

            @Override
            public void onConferenceWillJoin(Map<String, Object> map) {
                Log.e("jitsi", "即将加入会议");
            }

            @Override
            public void onConferenceJoined(Map<String, Object> map) {

                // 会议开始，记录开始时间
                startTime = System.currentTimeMillis();
                // 开始计时
                mCountDownTimer.start();
            }

            @Override
            public void onConferenceWillLeave(Map<String, Object> map) {
                Log.e(TAG, "5");
                // jitsi挂断可能需要一两秒的时间，
                DialogHelper.showMessageProgressDialog(Jitsi_connecting_second.this, getString(R.string.tip_handing_up));
                stopTime = System.currentTimeMillis();
                overCall((int) (stopTime - startTime) / 1000);
            }

            @Override
            public void onConferenceLeft(Map<String, Object> map) {
                Log.e(TAG, "6");
                DialogHelper.dismissProgressDialog();
                Jitsi_connecting_second.this.sendBroadcast(new Intent(CallConstants.CLOSE_FLOATING));
                finish();
            }
        });

        mScreenListener = new ScreenListener(this);
        mScreenListener.begin(new ScreenListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
            }

            @Override
            public void onScreenOff() {// 屏幕已锁定
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                    // 5.0屏幕锁定依然不能异常挂断，需手动挂断，否则Camera可能得不到正常释放，引起下次视频通话时的问题
                } else {
                    stopTime = System.currentTimeMillis();
                    overCall((int) (stopTime - startTime) / 1000);
                    finish();
                }
            }

            @Override
            public void onUserPresent() {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
        }
    }

    // 对方挂断
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(final MessageHangUpPhone message) {
        if (message.chatMessage.getFromUserId().equals(fromUserId)
                || message.chatMessage.getFromUserId().equals(toUserId)) {// 挂断方为当前通话对象 否则不处理
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                hideBottomUIMenu();
                return;
            }

            // 关闭悬浮窗
            sendBroadcast(new Intent(CallConstants.CLOSE_FLOATING));
            finish();
        }
    }

    /*******************************************
     * Method
     ******************************************/
    // 发送挂断的XMPP消息
    private void overCall(int time) {
        if (mCallType == 1) {
            EventBus.getDefault().post(new MessageEventCancelOrHangUp(CallTypeEnum.END_CONNECT_VOICE.getType(), toUserId,
                    "结束了语音通话",
                    time));
        } else if (mCallType == 2) {
            EventBus.getDefault().post(new MessageEventCancelOrHangUp(CallTypeEnum.END_CONNECT_VIDEO.getType(), toUserId,
                    "结束了视频通话",
                    time));
        }
    }

    private String formatTime() {
        Date date = new Date(new Date().getTime() - startTime);
        return mSimpleDateFormat.format(date);
    }

    // 隐藏虚拟按键
    private void hideBottomUIMenu() {
        View v = this.getWindow().getDecorView();
        v.setSystemUiVisibility(View.GONE);
    }

    /*******************************************
     * 生命周期
     ******************************************/
    @Override
    public void onBackPressed() {
        if (!JitsiMeetView.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        JitsiMeetView.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (JitsistateMachine.isFloating) {
            sendBroadcast(new Intent(CallConstants.CLOSE_FLOATING));
        }
    }

    @Override
    protected void onDestroy() {
        JitsistateMachine.reset();

        mJitsiMeetView.dispose();
        mJitsiMeetView = null;
        JitsiMeetView.onHostDestroy(this);

        EventBus.getDefault().unregister(this);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            if (connection != null) {
//                // 1.用户开启录屏之后未结束录屏就直接结束通话了，此时需要释放部分资源，否则下次录屏会引发崩溃
//                // 2.对方结束通话
//                if (recordService.isRunning()) {
//                    recordService.stopRecord();
//                }
//                unbindService(connection);
//            }
//        }

        if (mScreenListener != null) {
            mScreenListener.unregisterListener();
        }
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        Log.e(TAG, "onDestory");
        super.onDestroy();
    }
}
