package com.player.musicoo.activity

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import android.view.LayoutInflater
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.player.musicoo.R
import com.player.musicoo.media.MediaControllerManager
import com.player.musicoo.sp.AppStore
import com.player.musicoo.util.LogTag
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream

abstract class MoBaseActivity : AppCompatActivity(), CoroutineScope by MainScope() {

    enum class Event {
        ActivityStart,
        ActivityStop,
        ActivityOnResume
    }

    protected val TAG = LogTag.VO_ACT_LOG
    protected val appStore by lazy { AppStore(this) }
    protected val events = Channel<Event>(Channel.UNLIMITED)
    protected val meController = MediaControllerManager.getController()
    protected abstract suspend fun main()
    private var defer: suspend () -> Unit = {}
    private var deferRunning = false

    fun defer(operation: suspend () -> Unit) {
        this.defer = operation
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launch {
            main()
        }
    }

    override fun onResume() {
        super.onResume()
        events.trySend(Event.ActivityOnResume)
    }

    override fun onStart() {
        super.onStart()
        events.trySend(Event.ActivityStart)
    }

    override fun onStop() {
        super.onStop()
        events.trySend(Event.ActivityStop)
    }

    override fun finish() {
        if (deferRunning) {
            return
        }

        deferRunning = true

        launch {
            try {
                defer()
            } finally {
                withContext(NonCancellable) {
                    super.finish()
                }
            }
        }
    }

    suspend fun loadBitmapWithGlide(imageUrl: String): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                Glide.with(this@MoBaseActivity)
                    .asBitmap()
                    .load(imageUrl)
                    .submit() // 异步加载Bitmap
                    .get() // 阻塞等待获取Bitmap
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }

    fun applyGaussianBlur(inputBitmap: Bitmap, radius: Float, context: Context): Bitmap {
        val rsContext = RenderScript.create(context)
        val outputBitmap =
            Bitmap.createBitmap(inputBitmap.width, inputBitmap.height, inputBitmap.config)
        val blurScript = ScriptIntrinsicBlur.create(rsContext, Element.U8_4(rsContext))
        val tmpIn = Allocation.createFromBitmap(rsContext, inputBitmap)
        val tmpOut = Allocation.createFromBitmap(rsContext, outputBitmap)
        blurScript.setRadius(radius)
        blurScript.setInput(tmpIn)
        blurScript.forEach(tmpOut)
        tmpOut.copyTo(outputBitmap)
        rsContext.finish()
        return outputBitmap
    }

    fun loadBitmapFromAsset(id: Int): Bitmap {
        return try {
            val inputStream: InputStream = resources.openRawResource(id)
            BitmapFactory.decodeStream(inputStream)
        } catch (e: IOException) {
            e.printStackTrace()
            throw RuntimeException("Could not load bitmap from asset")
        }
    }

    fun showSongDescriptionDialog(description: String) {
        val inflater = LayoutInflater.from(this)
        val dialogView = inflater.inflate(R.layout.dialog_description, null)
        val title = dialogView.findViewById<TextView>(R.id.dialog_title)
        title.text = getString(R.string.description)
        val content = dialogView.findViewById<TextView>(R.id.dialog_content)
        content.text = description
        val close = dialogView.findViewById<RelativeLayout>(R.id.closeBtn)
        val dialogBuilder = AlertDialog.Builder(this)
            .setView(dialogView)
        val dialog = dialogBuilder.create()
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.show()
        close.setOnClickListener {
            dialog.dismiss()
        }
    }

    fun extractTextBeforeNewline(text: String): String {
        // 用换行符分割文本，取第一个部分
        return text.split("\n\n")[0]
    }

}