package com.bc_chat.im.activity

import android.graphics.Color
import android.graphics.Paint
import android.media.MediaPlayer
import android.support.v4.view.animation.LinearOutSlowInInterpolator
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.im.R
import com.bc_chat.im.databinding.ActivityVibrationDetailBinding
import com.zhaohaoting.framework.abs.BaseNoActionBarActivity
import com.zhaohaoting.framework.abs.contract.BaseContract
import com.zhaohaoting.framework.utils.DensityUtil
import com.zhaohaoting.framework.utils.glid.GlideUtils
import io.rong.common.RLog
import io.rong.eventbus.EventBus
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Group
import io.rong.imlib.model.Message
import io.rong.imlib.model.UserInfo

/**
 * author：Created by zhaohaoting on 2019/3/15
 * email：526309416@qq.com
 * desc：
 */
@Route(path = RouteConfig.VIBRATION_DETAILS_ACTIVITY)
class VibrationDetailsActivity : BaseNoActionBarActivity<BaseContract.BasePresenter>() {

    private var mediaPlayer: MediaPlayer? = null

    private val binding by lazy {
        rootDataBinding as ActivityVibrationDetailBinding
    }
    private val message by lazy {
        intent.getParcelableExtra<Message>("message")
    }

    private var userInfo: UserInfo? = null
    private var group: Group? = null

    override fun onInit() {
        vibration()
        if (message.conversationType == Conversation.ConversationType.PRIVATE) {
            val senderUserId = message.senderUserId
            userInfo = RongUserInfoManager.getInstance().getUserInfo(senderUserId)
            setViewData(userInfo = userInfo)
        } else if (message.conversationType == Conversation.ConversationType.GROUP) {
            val targetId = message.targetId
            group = RongUserInfoManager.getInstance().getGroupInfo(targetId)
            setViewData(groupInfo = group)
        }
        binding.tvVibratIgnore.setOnClickListener {
            finish()
        }
        binding.tvVibratReceive.setOnClickListener {
            if (message.conversationType == Conversation.ConversationType.PRIVATE) {
                ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, message.conversationType, userInfo?.userId!!, userInfo?.name!!, null)
            } else if (message.conversationType == Conversation.ConversationType.GROUP) {
                ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, message.conversationType, message.targetId, group?.name!!, null)
            }
            finish()
        }
        binding.waveView.setInitialRadius(DensityUtil.dip2px(this, 35f).toFloat())
        binding.waveView.setDuration(2000)
        binding.waveView.setStyle(Paint.Style.FILL)
        binding.waveView.setColor(Color.parseColor("#ffffff"))
        binding.waveView.setInterpolator(LinearOutSlowInInterpolator())
        startWave()
        EventBus.getDefault().register(this)
    }

    private fun setViewData(groupInfo: Group? = null, userInfo: UserInfo? = null) {
        if (userInfo != null) {
            GlideUtils.loadCircleImage(this, if (userInfo.portraitUri == null) "" else userInfo.portraitUri.toString(), binding.ivHeader)
            binding.tvNickName.text = userInfo.name
            binding.tvDesc.text = "${userInfo.name}想和你聊聊"
        }
        if (groupInfo != null) {
            GlideUtils.loadCircleImage(this, if (groupInfo.portraitUri == null) "" else groupInfo.portraitUri.toString(), binding.ivHeader)
            binding.tvNickName.text = groupInfo.name
            binding.tvDesc.text = "${groupInfo.name} 群主"
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_vibration_detail
    }

    override fun initPresenter(): BaseContract.BasePresenter? {
        return null
    }

    fun onEventMainThread(groupInfo: Group) {
        if (groupInfo.id.equals(message.targetId)) {
            this.group = groupInfo
            setViewData(groupInfo = groupInfo)
        }
    }

    fun onEventMainThread(userInfo: UserInfo) {
        if (userInfo.userId.equals(message.senderUserId)) {
            this.userInfo = userInfo
            setViewData(userInfo = userInfo)
        }
    }

    fun stopWave() {
        binding.waveView.stop()
    }


    fun startWave() {
        binding.waveView.start()
    }

    private fun vibration() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer?.stop()
                mediaPlayer?.reset()
                mediaPlayer?.release()
                mediaPlayer = null
            }
            mediaPlayer = MediaPlayer.create(this, R.raw.vibration)
            mediaPlayer?.start()
            mediaPlayer?.setOnCompletionListener { mp ->
                if (mp != null) {
                    try {
                        mp.stop()
                        mp.reset()
                        mp.release()
                    } catch (var3: Exception) {
                        RLog.e("MyMessageNotificationManager", "sound", var3)
                    }
                }
                if (mediaPlayer != null) {
                    mediaPlayer = null
                }
            }
        } catch (var3: Exception) {
            RLog.e("MyMessageNotificationManager", "sound", var3)
            if (mediaPlayer != null) {
                mediaPlayer = null
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mediaPlayer != null) {
            mediaPlayer?.stop()
            mediaPlayer?.reset()
            mediaPlayer?.release()
            mediaPlayer = null
        }
        EventBus.getDefault().unregister(this)
    }
}
