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.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rv.im.Constants;
import com.rv.im.ImSetting;
import com.rv.im.R;
import com.rv.im.call.event.MessageBusyEvent;
import com.rv.im.call.event.MessageEventCancelOrHangUp;
import com.rv.im.call.event.MessageEventSipPreview;
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 Jitsi_pre extends AppCompatActivity {
    Timer timer = new Timer();
    private String mLoginUserId;
    private String mLoginUserName;
    private boolean isAudio;
    private String call_toUser;
    private String call_toName;
    private String meetUrl;
    private AssetFileDescriptor mAssetFileDescriptor;
    private MediaPlayer mediaPlayer;
    TimerTask timerTask = new TimerTask() {//  单聊 拨号界面 三十秒内 对方未接听  发送挂断消息 结束当前页面
        @Override
        public void run() {
            runOnUiThread(() -> {
                abort();
                if (isAudio) {
                    EventBus.getDefault().post(new MessageEventCancelOrHangUp(CallTypeEnum.END_CONNECT_VOICE.getType(), call_toUser,
                            "无人接听", 0));
                } else {
                    EventBus.getDefault().post(new MessageEventCancelOrHangUp(CallTypeEnum.END_CONNECT_VIDEO.getType(), call_toUser,
                            "无人接听", 0));
                }
                JitsistateMachine.reset();
                finish();
            });
        }
    };
    private ImageView mCallAvatar;
    private TextView mCallName;
    private ImageButton mHangUp;
    private boolean isAllowBack = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_call_incall_false);
        initData();
        initView();
        timer.schedule(timerTask, 30000, 30000);// 开启计时器
        EventBus.getDefault().register(this);
    }

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

        isAudio = getIntent().getBooleanExtra("isvoice", false);
        call_toUser = getIntent().getStringExtra("touserid");
        call_toName = getIntent().getStringExtra("username");
        meetUrl = getIntent().getStringExtra("meetUrl");

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

        bell();// 响铃
    }

    private void initView() {
        mCallAvatar = findViewById(R.id.call_avatar);
        mCallName = findViewById(R.id.call_name);
        mHangUp = findViewById(R.id.call_hang_up);
        TextView wait_tv = findViewById(R.id.call_wait);
        TextView hang_up_tv = findViewById(R.id.call_hang_up_tv);
        wait_tv.setText("正在等待对方接受邀请");
        hang_up_tv.setText("挂断");
//        AvatarHelper.getInstance().displayAvatar(call_toUser, mCallAvatar, true);
        mCallName.setText(call_toName);
        // 主动挂断
        mHangUp.setOnClickListener(view -> {
            abort();
            sendHangUpMessage();
            if (isAudio) {
                EventBus.getDefault().post(new MessageEventCancelOrHangUp(CallTypeEnum.NO_CONNECT_VOICE.getType(), call_toUser,
                        "取消了语音通话", 0));
            } else {
                EventBus.getDefault().post(new MessageEventCancelOrHangUp(CallTypeEnum.NO_CONNECT_VIDEO.getType(), call_toUser,
                        "取消了视频通话", 0));
            }
            JitsistateMachine.reset();
            finish();
        });
    }

    private void sendHangUpMessage() {
        ChatMessage message = new ChatMessage();
        if (isAudio) {
            message.setMessageType(MessageTypeEnum.VOLTE_CALL);
            message.setCallType(CallTypeEnum.END_CONNECT_VOICE);
        } else {
            message.setMessageType(MessageTypeEnum.VIDEO_CALL);
            message.setCallType(CallTypeEnum.END_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("挂断了通话");
        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);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busyEventBus(final MessageBusyEvent message) {

        if (message != null && message.chatMessage != null && !TextUtils.isEmpty(message.chatMessage.getFromUserId())
                && message.chatMessage.getFromUserId().equals(call_toUser)) {
            Toast.makeText(this, R.string.tip_opposite_busy_call, Toast.LENGTH_SHORT).show();
            abort();
            JitsistateMachine.reset();
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(final MessageEventSipPreview message) {// 对方接听
        abort();
        Intent intent = new Intent(this, Jitsi_connecting_second.class);
        if (message.isvoice) {
            intent.putExtra("type", 1);
        } else {
            intent.putExtra("type", 2);
        }
        intent.putExtra("fromuserid", mLoginUserId);
        intent.putExtra("touserid", call_toUser);
        if (!TextUtils.isEmpty(meetUrl)) {
            intent.putExtra("meetUrl", meetUrl);
        }
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);// 淡入淡出动画
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(final MessageHangUpPhone message) {// 对方拒接
        if (message.chatMessage.getFromUserId().equals(call_toUser)) {
            abort();
            JitsistateMachine.reset();
            setResult(RESULT_OK);
            finish();
        }
    }

    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 (IOException e) {
            e.printStackTrace();
        }
        EventBus.getDefault().unregister(this);
    }
}
