package com.baijiayun.live.ui.topmenu

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.baijiayun.bjyutils.kt.dp
import com.baijiayun.bjyutils.kt.getFormatterTime
import com.baijiayun.live.ui.R
import com.baijiayun.livebase.base.getActivityViewModel
import com.baijiayun.livebase.base.getViewModel
import com.baijiayun.livebase.context.LPConstants
import com.baijiayun.livebase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.base.BasePadFragment
import com.baijiayun.liveuibase.base.LiveRoomActivity
import com.baijiayun.liveuibase.listeners.CallbackManager
import com.baijiayun.liveuibase.utils.enableVideoPreviewBeforeClass
import com.baijiayun.liveuibase.viewmodel.LiveRoomViewModel
import com.baijiayun.liveuibase.viewmodel.TopMenuViewModel
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_broadcast
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_downlossrate
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_exit
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_icon_container
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_record
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_report
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_setting
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_share
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_time
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_title
import kotlinx.android.synthetic.main.fragment_pad_top_menu.fragment_pad_top_menu_uplossrate

/**
 * Created by Shubo on 2019-10-10.
 */
class TopMenuFragment : BasePadFragment() {

    private val topMenuViewModel by lazy { getViewModel { TopMenuViewModel(routerViewModel.liveRoom) } }
    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                fragment_pad_top_menu_title.text = routerViewModel.liveRoom.roomInfo.title
                topMenuViewModel.subscribe()
                initSuccess()
            }
        }
    }
    private val broadcastStatusObserver by lazy {
        Observer<Boolean> {
            fragment_pad_top_menu_broadcast.isChecked = it
        }
    }

    private lateinit var liveRoomViewModel: LiveRoomViewModel

    companion object {
        fun newInstance() = TopMenuFragment()
    }

    override fun getLayoutId(): Int = R.layout.fragment_pad_top_menu

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    override fun init(view: View) {
        liveRoomViewModel = getActivityViewModel {
            LiveRoomViewModel(routerViewModel)
        }
    }

    override fun observeActions() {
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
        routerViewModel.broadcastStatus.observeForever(broadcastStatusObserver)
        routerViewModel.isClassStarted.observe(this){
            if (it) {
                fragment_pad_top_menu_setting.visibility = View.VISIBLE
            }
        }
        topMenuViewModel.classStartTime.observe(this) {
            fragment_pad_top_menu_time.text = when (it) {
                -2 -> {
                    getString(R.string.bjy_base_live_end)
                }
                -1 -> {
                    getString(R.string.bjy_base_live_not_start)
                }
                else -> {
                    getString(R.string.bjy_base_living_risk, getFormatterTime(it))
                }
            }
        }
        topMenuViewModel.downLinkLossRate.observe(this) {
            it?.let {
                fragment_pad_top_menu_downlossrate.text = it.first
                context?.run {
                    fragment_pad_top_menu_downlossrate.setTextColor(
                        ContextCompat.getColor(
                            this,
                            it.second
                        )
                    )
                }
            }
        }
        topMenuViewModel.upLinkLossRate.observe(this) {
            it?.let {
                fragment_pad_top_menu_uplossrate.text = it.first
                context?.run {
                    fragment_pad_top_menu_uplossrate.setTextColor(
                        ContextCompat.getColor(
                            this,
                            it.second
                        )
                    )
                }
            }
        }

        liveRoomViewModel.recordStatus.observe(this) {
            it?.let {
                fragment_pad_top_menu_record.isChecked =
                    it.status == LPConstants.CloudRecordStatus.Recording.status

            }
        }
    }

    private fun initSuccess() {
        if (enableVideoPreviewBeforeClass(routerViewModel) || routerViewModel.liveRoom.isAudition) {
            fragment_pad_top_menu_setting.visibility = View.GONE
        }
        //老师助教与学生读取不同配置项
        fragment_pad_top_menu_record.visibility =
            if (routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Student || routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Visitor) {
                if (routerViewModel.liveRoom.partnerConfig.liveHideRecordStatus == 1 || routerViewModel.liveRoom.partnerConfig.useSecretCloudRecord) View.GONE
                else View.VISIBLE
            } else {
                if (routerViewModel.liveRoom.partnerConfig.disableLiveRoomBottomMenus.split(",").contains("cloud_record") || routerViewModel.liveRoom.partnerConfig.useSecretCloudRecord) View.GONE
                else View.VISIBLE
            }
        routerViewModel.isShowShare.observe(this) {
            it?.let {
                fragment_pad_top_menu_share.visibility =
                    if (it && routerViewModel.liveRoom.partnerConfig.enableShare) View.VISIBLE else View.GONE
            }
        }
        routerViewModel.isEnableBroadcast.observe(this) {
            fragment_pad_top_menu_broadcast.visibility =
                if (it && routerViewModel.liveRoom.partnerConfig.liveRoomBroadcast && routerViewModel.liveRoom.isTeacher) View.VISIBLE else View.GONE
        }
    }

    private fun initView() {
        if (routerViewModel.liveRoom.isAudition) {
            fragment_pad_top_menu_icon_container.visibility = View.GONE
        }
        fragment_pad_top_menu_exit.setOnClickListener {
            if (CallbackManager.getInstance().exitListener != null) {
                if (activity is LiveRoomActivity) {
                    (activity as LiveRoomActivity).onRoomExit()
                }
            } else {
                routerViewModel.actionExit.value = Unit
            }
        }
        fragment_pad_top_menu_setting.setOnClickListener {
            routerViewModel.action2Setting.value = Unit
        }
        fragment_pad_top_menu_share.setOnClickListener { routerViewModel.action2Share.value = Unit }
        fragment_pad_top_menu_record.setOnClickListener {
            if (routerViewModel.liveRoom.currentUser.type != LPConstants.LPUserType.Teacher
                && routerViewModel.liveRoom.currentUser.type != LPConstants.LPUserType.Assistant
            ) {
                return@setOnClickListener
            }
            if (routerViewModel.isClassStarted.value != true) {
                if (routerViewModel.liveRoom.isTeacher) {
                    showToastMessage(getString(R.string.pad_class_start_tip))
                } else {
                    showToastMessage(getString(R.string.live_course_not_begin))
                }
                return@setOnClickListener
            }
            if (if (liveRoomViewModel.recordStatus.value == null) false else liveRoomViewModel.recordStatus.value?.status == LPConstants.CloudRecordStatus.Recording.status) {
                context?.let {
                    ThemeMaterialDialogBuilder(it)
                        .apply {
                            title(getString(R.string.live_exit_hint_title))
                            content(getString(R.string.live_cloud_recording_content))
                            contentColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_assistant_text_color))
                        }
                        .apply {
                            positiveText(getString(R.string.live_cloud_record_setting_end))
                            positiveColorRes(R.color.base_warning_color)
                            onPositive { _, _ -> liveRoomViewModel.switchCloudRecord() }
                        }
                        .apply {
                            negativeText(getString(R.string.base_cancel))
                            onNegative { dialog, _ -> dialog.dismiss() }
                        }
                        .build().show()
                }
            } else {
                liveRoomViewModel.switchCloudRecord()
            }
        }
        fragment_pad_top_menu_broadcast.setOnClickListener {
            if (!routerViewModel.liveRoom.isClassStarted) {
                showToastMessage(getString(R.string.bjy_live_broadcast_not_start_tip))
                return@setOnClickListener
            }
            if (routerViewModel.broadcastStatus.value == true) {
                context?.let {
                    ThemeMaterialDialogBuilder(it)
                            .apply {
                                title(getString(R.string.live_exit_hint_title))
                                content(getString(R.string.bjy_live_broadcast_content))
                                contentColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_assistant_text_color))
                            }
                            .apply {
                                positiveText(getString(R.string.bjy_live_broadcast_end))
                                positiveColorRes(R.color.base_warning_color)
                                onPositive { _, _ -> routerViewModel.actionSwitchBroadcast.value = Unit }
                            }
                            .apply {
                                negativeText(getString(R.string.base_cancel))
                                onNegative { dialog, _ -> dialog.dismiss() }
                            }
                            .build().show()
                }
            } else {
                routerViewModel.actionSwitchBroadcast.value = Unit
            }
        }
        fragment_pad_top_menu_report.setOnClickListener {
            context?.run {
                routerViewModel.action2Report.postValue(null)
            }
        }
        context?.let {
            val upLinkDrawable = VectorDrawableCompat.create(resources, R.drawable.base_ic_uplink_pad, null)
            upLinkDrawable?.setBounds(0, 0, 16.dp, 16.dp)
            fragment_pad_top_menu_uplossrate.setCompoundDrawables(upLinkDrawable, null, null, null)
            val downLinkDrawable = VectorDrawableCompat.create(resources, R.drawable.base_ic_downlink_pad, null)
            downLinkDrawable?.setBounds(0, 0, 16.dp, 16.dp)
            fragment_pad_top_menu_downlossrate.setCompoundDrawables(downLinkDrawable, null, null, null)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
        routerViewModel.broadcastStatus.removeObserver(broadcastStatusObserver)
    }
}