package com.rv.im.call;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.rv.im.Constants;
import com.rv.im.ImSetting;
import com.rv.im.R;
import com.rv.im.call.event.MessageHangUpPhone;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.CallTypeEnum;
import com.rv.im.enums.MessageStatusEnum;
import com.rv.im.enums.MessageTypeEnum;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


/**
 * 来电显示
 */
public class JitsiIncomingcall extends AppCompatActivity implements View.OnClickListener {
    Timer timer = new Timer();
    private String mLoginUserId;
    private String mLoginUserName;
    private int mCallType;
    private String call_fromUser;
    private String call_toUser;
    private String call_Name;
    private String meetUrl;

    private AssetFileDescriptor mAssetFileDescriptor;
    private MediaPlayer mediaPlayer;
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(() -> {
                abort();
                if (mCallType == 1 || mCallType == 2) {//  来电界面显示 三十秒内 不主动响应  发送挂断消息给对方
                    sendHangUpMessage("无人接听您的语音");
                }
                JitsistateMachine.reset();
                finish();
            });
        }
    };
    private ImageView mInviteAvatar;
    private TextView mInviteName;
    private TextView mInviteInfo;
    private ImageButton mAnswer; // 接听
    private ImageButton mHangUp; // 挂断
    private boolean isAllowBack = false;

    @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.view_call_trying);
        initData();
        initView();
        timer.schedule(timerTask, 30000, 30000);
        EventBus.getDefault().register(this);
    }

    private void initData() {
        mLoginUserId = ImSetting.getUserId();
        mLoginUserName = ImSetting.getUserName();

        mCallType = getIntent().getIntExtra(CallConstants.AUDIO_OR_VIDEO_OR_MEET, 0);
        call_fromUser = getIntent().getStringExtra("fromuserid");
        call_toUser = getIntent().getStringExtra("touserid");
        call_Name = getIntent().getStringExtra("name");
        meetUrl = getIntent().getStringExtra("meetUrl");

        JitsistateMachine.isInCalling = true;
        JitsistateMachine.callingOpposite = call_toUser;

        bell();
    }

    private void initView() {
        mInviteAvatar = findViewById(R.id.call_avatar);
        mInviteName = findViewById(R.id.call_name);
        mInviteInfo = findViewById(R.id.call_invite_type);
        mAnswer = findViewById(R.id.call_answer);
        mHangUp = findViewById(R.id.call_hang_up);
        mInviteName.setText(call_Name);
        if (mCallType == 1) {
            mInviteInfo.setText(getString(R.string.suffix_invite_you_voice));
        } else if (mCallType == 2) {
            mInviteInfo.setText(getString(R.string.suffix_invite_you_video));
        } else if (mCallType == 3) {
            mInviteInfo.setText(getString(R.string.tip_invite_voice_meeting));
        } else if (mCallType == 4) {
            mInviteInfo.setText(getString(R.string.tip_invite_video_meeting));
        }
        mAnswer.setOnClickListener(this);
        mHangUp.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();// 接听
        if (i == R.id.call_answer) {
            abort();
//            if (coreManager.isLogin()) {
            if (mCallType == 1 || mCallType == 2) {// 通话 接听 告诉 对方，会议不需要
                sendAnswerMessage();
            }
            Intent intent = new Intent(this, Jitsi_connecting_second.class);
//            if (mCallType == 1) {
//                intent.putExtra("type", 1);
//            } else if (mCallType == 2) {
//                intent.putExtra("type", 2);
//            } else if (mCallType == 3) {
//                intent.putExtra("type", 3);
//            } else if (mCallType == 4) {
//                intent.putExtra("type", 4);
//            }
            intent.putExtra("type", mCallType);
            intent.putExtra("fromuserid", call_fromUser);
            intent.putExtra("touserid", call_toUser);
            if (!TextUtils.isEmpty(meetUrl)) {
                intent.putExtra("meetUrl", meetUrl);
            }
            startActivity(intent);
            finish();
//            }

        } else if (i == R.id.call_hang_up) {
            abort();
//            if (coreManager.isLogin()) {
            if (mCallType == 1 || mCallType == 2) {// 通话 拒绝 告诉 对方，会议不需要
                sendHangUpMessage("拒绝了你的通话");
            }
//            }
            JitsistateMachine.reset();
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(MessageHangUpPhone message) {// 对方取消了 || 其他端 (接听 || 取消)了
        if (message.chatMessage.getFromUserId().equals(call_toUser)
                || message.chatMessage.getFromUserId().equals(mLoginUserId)) {
            abort();
            JitsistateMachine.reset();
            finish();
            /*if (isSipback) {// 当app处于关闭状态收到来电，通话结束后终止程序
                ActivityStack.getInstance().exit();
                android.os.Process.killProcess(android.os.Process.myPid());
            }*/
        }
    }

    private void sendAnswerMessage() {
        ChatMessage message = new ChatMessage();
        if (mCallType == 1) {
            message.setMessageType(MessageTypeEnum.VOLTE_CALL);
            message.setCallType(CallTypeEnum.CONNECTED_VOICE);
        } else if (mCallType == 2) {
            message.setMessageType(MessageTypeEnum.VIDEO_CALL);
            message.setCallType(CallTypeEnum.CONNECTED_VIDEO);
        }
        message.setContent("");
        message.setFromUserId(mLoginUserId);
        message.setToUserId(call_toUser);
        message.setPackId(UUID.randomUUID().toString().replaceAll("-", ""));
        message.setFromUserName(mLoginUserName);
        message.setTimeSend(System.currentTimeMillis());
        sendMsgBroad(call_toUser, message);
    }

    public void sendMsgBroad(String call_toUser, ChatMessage message) {
        Intent intent = new Intent();
        intent.setAction(Constants.ACTIONS.ACTION_SEND_RECEIVER);
        intent.setPackage(getPackageName());
        intent.putExtra(Constants.KEYS.KEY_MESSAGE_TARGET, call_toUser);
        intent.putExtra(Constants.KEYS.KEY_MESSAGE_CONTENT, message.toJsonString());
        sendBroadcast(intent);
    }

    private void sendHangUpMessage(String content) {
        ChatMessage message = new ChatMessage();
        if (mCallType == 1) {
            message.setMessageType(MessageTypeEnum.VOLTE_CALL);
            message.setCallType(CallTypeEnum.NO_CONNECT_VOICE);
        } else if (mCallType == 2) {
            message.setMessageType(MessageTypeEnum.VIDEO_CALL);
            message.setCallType(CallTypeEnum.NO_CONNECT_VIDEO);
        }

        message.setMessageStatus(MessageStatusEnum.SENDING);
        message.setFromUserId(mLoginUserId);
        message.setFromUserName(mLoginUserName);
        message.setToUserId(call_toUser);
        message.setPackId(UUID.randomUUID().toString().replaceAll("-", ""));
        message.setTimeSend(System.currentTimeMillis());
        message.setContent(content);
        sendMsgBroad(call_toUser, message);
    }

    private void bell() {
        try {
            mAssetFileDescriptor = getAssets().openFd("dial.mp3");
            mediaPlayer = new MediaPlayer();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(mAssetFileDescriptor.getFileDescriptor(), mAssetFileDescriptor.getStartOffset(), mAssetFileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(arg0 -> {
                mediaPlayer.start();
                mediaPlayer.setLooping(true);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void abort() {
        if (timer != null) {
            timer.cancel();
        }
        try {
            mediaPlayer.stop();
        } catch (Exception e) {
        }
        mediaPlayer.release();
    }

    @Override
    public void onBackPressed() {
        if (isAllowBack) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mAssetFileDescriptor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        EventBus.getDefault().unregister(this);
    }
}
