package com.baijiayun.live.ui.pptpanel.pptmanage

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.baijia.bjydialog.DialogAction
import com.baijia.bjydialog.MaterialDialog
import com.baijiayun.bjyutils.toast.ToastCompat
import com.baijiayun.live.ui.R
import com.baijiayun.livecore.models.LPDocModel
import com.baijiayun.livecore.models.LPUploadDocModel
import com.baijiayun.livecore.models.LPUploadHomeworkUserModel
import com.baijiayun.livecore.models.courseware.LPMediaCoursewareModel
import com.baijiayun.livecore.models.file.cloudfile.LPCloudFileModel
import com.baijiayun.livecore.models.roomresponse.LPAllowUploadHomeworkModel
import com.baijiayun.liveuibase.base.LiveRoomBaseActivity
import com.baijiayun.liveuibase.viewmodel.RouterViewModel
import com.baijiayun.liveuibase.widgets.courseware.BaseCourseWareContract.BaseCourseWarePresenter
import com.baijiayun.liveuibase.widgets.courseware.BaseCourseWareFragment
import com.baijiayun.liveuibase.widgets.courseware.CourseManagePresenter
import com.baijiayun.liveuibase.widgets.courseware.ICourseWareViewListener
import com.baijiayun.liveuibase.widgets.courseware.models.UploadDocModel
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder
import kotlin.math.max

class PPTManageWindow : BaseCourseWareFragment() {
    private var routerViewModel: RouterViewModel? = null
    private var pageIndexCaches: MutableMap<String, Int>? = null

    override fun initChildData() {
        pageIndexCaches = HashMap()
        if (context is LiveRoomBaseActivity) {
            routerViewModel =
                ViewModelProvider(context as LiveRoomBaseActivity).get(RouterViewModel::class.java)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = super.onCreateView(inflater, container, savedInstanceState)
        presenter.subscribe(routerViewModel!!.liveRoom)
        return view
    }

    override fun initCourseWareViewListener(): ICourseWareViewListener {
        return object : ICourseWareViewListener {
            override fun onClose() {
                routerViewModel!!.actionShowPPTManager.value = false
            }

            override fun onPlayImg(uploadDocModel: LPUploadDocModel) {
                playDoc(uploadDocModel.fileId.toString())
            }

            override fun onReminderMsg(msg: String) {
                ToastCompat.showToast(getContext(), msg, Toast.LENGTH_SHORT)
            }

            override fun onRemindHomeworkSupport() {
                ThemeMaterialDialogBuilder(context)
                    .content(R.string.base_course_manage_homework_support_remind_text)
                    .positiveText(R.string.base_live_i_know)
                    .negativeText(R.string.base_do_not_remind)
                    .onNegative { _: MaterialDialog?, _: DialogAction? ->
                        homeworkRemindStatus = HomeworkRemindStatus.DO_NOT_REMIND
                    }
                    .autoDismiss(true).build().show()
            }

            override fun onDeleteDoc(fid: String, isReUpload: Boolean) {
                if (isReUpload) {
                    routerViewModel!!.liveRoom.docListVM.deleteDocument(fid)
                } else {
                    ThemeMaterialDialogBuilder(context)
                        .content(R.string.base_course_manage_delete_doc_reminder)
                        .positiveText(R.string.base_course_manage_delete_confirm)
                        .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                        .onPositive { _: MaterialDialog?, _: DialogAction? ->
                            routerViewModel!!.liveRoom.docListVM.deleteDocument(
                                fid
                            )
                        }
                        .negativeText(R.string.base_cancel)
                        .autoDismiss(true).build().show()
                }
            }

            override fun onDeleteMediaCourseware(fid: String?) {
                // do nothing
            }

            override fun onDeleteCloudFile(cloudFileModel: LPCloudFileModel) {
                ThemeMaterialDialogBuilder(context)
                    .content(R.string.base_course_manage_delete_doc_reminder)
                    .positiveText(R.string.base_course_manage_delete_confirm)
                    .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                    .onPositive { _: MaterialDialog?, _: DialogAction? ->
                        routerViewModel!!.liveRoom.cloudFileVM.deleteCloudFile(
                            cloudFileModel.fileId
                        )
                    }
                    .negativeText(R.string.base_cancel)
                    .autoDismiss(true).build().show()
            }

            override fun onDeleteHomework(homeworkId: String) {
                ThemeMaterialDialogBuilder(context)
                    .content(R.string.base_course_manage_delete_homework_reminder)
                    .positiveText(R.string.base_course_manage_delete_confirm)
                    .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                    .onPositive { _: MaterialDialog?, _: DialogAction? ->
                        presenter.deleteHomework(
                            homeworkId,
                            LPUploadHomeworkUserModel.copyData(routerViewModel!!.liveRoom.currentUser)
                        )
                    }
                    .negativeText(R.string.base_cancel)
                    .autoDismiss(true).build().show()
            }

            override fun onCancelTransfer(uploadDocModel: UploadDocModel) {
                ThemeMaterialDialogBuilder(context)
                    .content(R.string.base_course_manage_cancel_transfer_reminder)
                    .positiveText(R.string.base_course_manage_delete_confirm)
                    .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                    .onPositive { _: MaterialDialog?, _: DialogAction? ->
                        presenter.deleteTranslating(
                            uploadDocModel
                        )
                    }
                    .negativeText(R.string.base_cancel)
                    .autoDismiss(true).build().show()
            }

            override fun onUpdateAllowUploadHomework(isAllow: Boolean) {
                routerViewModel!!.liveRoom.docListVM.requestUpdateAllowUploadHomework(
                    LPAllowUploadHomeworkModel(isAllow)
                )
            }

            override fun requestLoadNextPage(keyword: String) {
                routerViewModel!!.liveRoom.docListVM.requestNextPageHomework(keyword)
            }
        }
    }

    override fun initPresenter(): BaseCourseWarePresenter {
        return object : CourseManagePresenter(this) {
            override fun playDoc(docModel: LPDocModel): Boolean {
                return this@PPTManageWindow.playDoc(docModel.docId)
            }

            override fun playMediaCourseware(toPlayMedia: LPMediaCoursewareModel?) {
                ToastCompat.showToast(
                    this@PPTManageWindow.context,
                    this@PPTManageWindow.context.getString(R.string.base_course_manage_file_type_not_support_play),
                    Toast.LENGTH_LONG
                )
            }

            override fun playBds(bdsModel: LPDocModel) {
                // do nothing
            }

            override fun previewDoc(docModel: LPDocModel?) {
                // do nothing
            }
        }
    }

    private fun playDoc(docId: String): Boolean {
        val page: Int
        val index = pageIndexCaches!![docId]
        page = index ?: findDocListFirstPage(docId)
        routerViewModel?.notifyPPTPageCurrent?.value = page
        return true
    }

    private fun findDocListFirstPage(docId: String): Int {
        val docList = routerViewModel!!.liveRoom.docListVM.docList
        var pageTotal: Int
        var i = 0
        while (i < docList.size) {
            val docModel = docList[i]
            pageTotal = docModel.totalPage
            pageIndexCaches!![docModel.docId] = docModel.page
            i += max(1, pageTotal)
        }
        val index = pageIndexCaches!![docId]
        return index ?: 0
    }

    override fun getLiveRoom() = routerViewModel?.liveRoom

    override fun onDestroy() {
        super.onDestroy()
        routerViewModel = null
    }
}