package com.tencent.liteav.demo.player

import android.content.pm.PackageManager
import android.graphics.Typeface.DEFAULT_BOLD
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import com.tencent.liteav.demo.player.ui.MenuItemView
import com.tencent.liteav.demo.player.util.ModelProvider
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.*
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.util.*


class PlayerShare : AppCompatActivity(), CoroutineScope by MainScope() {
    private lateinit var shareFriend: MenuItemView
    private lateinit var shareTimeline: MenuItemView
    private lateinit var backButton: ImageView

    private val shareContext get() = this@PlayerShare

    private lateinit var api: IWXAPI
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(createView())

        window.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
        )

        val appInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
        val wechatAppId = appInfo.metaData.getString("weChatAppId")
        api = WXAPIFactory.createWXAPI(applicationContext, wechatAppId)
    }

    private fun createView(): View {
        val root = RelativeLayout(shareContext).apply {
            id = View.generateViewId()
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
            )

            val subRoot = ConstraintLayout(shareContext).apply {
                id = View.generateViewId()
                layoutParams = RelativeLayout.LayoutParams(
                    shareContext.resources.getDimension(R.dimen.layour_share_width).toInt(),
                    ViewGroup.LayoutParams.MATCH_PARENT,
                ).apply {
                    addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
                }

                val parent = this

                background =
                    AppCompatResources.getDrawable(shareContext, R.drawable.menu_background)

                shareFriend = MenuItemView(shareContext).apply {
                    setTitle("微信")
                    setIcon(R.mipmap.share_session)
                    id = View.generateViewId()
                }

                shareTimeline = MenuItemView(shareContext).apply {
                    setTitle("朋友圈")
                    setIcon(R.mipmap.share_timeline)
                    id = View.generateViewId()
                }

                backButton = ImageView(shareContext)

                backButton.apply {
                    setImageResource(R.mipmap.item_back)

                    id = View.generateViewId()
                    layoutParams = ConstraintLayout.LayoutParams(
                        shareContext.resources.getDimension(R.dimen.menu_back_width).toInt(),
                        shareContext.resources.getDimension(R.dimen.menu_back_height).toInt(),
                    ).apply {
                        leftToLeft = parent.id
                        topToTop = parent.id
                        bottomToBottom = parent.id
                    }
                    setOnClickListener {
                        shareContext.finish()
                    }
                }

                val textView = TextView(shareContext).apply {
                    text = "分享"
                    id = View.generateViewId()

                    layoutParams = ConstraintLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                    ).apply {
                        leftToRight = backButton.id
                        rightToRight = parent.id
                        topToTop = parent.id
                        topMargin = shareContext.resources.getDimension(R.dimen.dp40).toInt()
                    }
                    textSize = 20f
                    typeface = DEFAULT_BOLD
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        lineHeight = shareContext.resources.getDimension(R.dimen.dp28).toInt()
                    }

                }

                shareFriend.apply {
                    layoutParams = ConstraintLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                    ).apply {
                        leftToRight = backButton.id
                        topToBottom = textView.id
                        rightToLeft = shareTimeline.id
                        topMargin = shareContext.resources.getDimension(R.dimen.dp37).toInt()
                    }

                    setOnClickListener { shareSession() }
                }

                shareTimeline.apply {
                    layoutParams = ConstraintLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                    ).apply {
                        leftToRight = shareFriend.id
                        topToBottom = textView.id
                        rightToRight = parent.id
                        topMargin = shareContext.resources.getDimension(R.dimen.dp37).toInt()
                    }

                    setOnClickListener { shareTimeline() }
                }


                addView(backButton)
                addView(textView)
                addView(shareFriend)
                addView(shareTimeline)
            }

            addView(subRoot)
        }

        return root
    }

    private fun shareSession() {
        internalShare(SendMessageToWX.Req.WXSceneSession)
    }

    private fun shareTimeline() {
        internalShare(SendMessageToWX.Req.WXSceneTimeline)
    }

    private fun internalShare(scene:Int){
        val webpage = WXWebpageObject()
        webpage.webpageUrl = ModelProvider.cccccc.shareUrl

        val msg = WXMediaMessage(webpage)
        msg.title = ModelProvider.cccccc.name
        msg.description = ModelProvider.cccccc.description

        launch {
            msg.thumbData = readByteArray(ModelProvider.cccccc.imgCover)
            val req = SendMessageToWX.Req()
            req.transaction = UUID.randomUUID().toString().replace("-", "")
            req.message = msg
            req.scene = scene

            api.sendReq(req)
        }
    }

    private suspend fun readByteArray(url: String): ByteArray = withContext(Dispatchers.IO) {
        val okHttpClient = OkHttpClient.Builder().build()
        val request: Request = Request.Builder().url(url).get().build()
        try {
            val response = okHttpClient.newCall(request).execute()
            val responseBody = response.body
            if (response.isSuccessful && responseBody != null) {
                responseBody.bytes()
            } else {
                byteArrayOf()
            }
        } catch (e: IOException) {
            byteArrayOf()
        }
    }
}