package com.base.appzxhy.push.notification

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Shader
import androidx.core.graphics.createBitmap
import com.base.appzxhy.bean.push.NotificationInfoBean
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mbridge.msdk.thrid.okhttp.OkHttpClient
import com.mbridge.msdk.thrid.okhttp.Request
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.util.LinkedList

/**
 * 处理推送用到bean类
 */
object NotificationBeanUtils {

    var notificationQueue = LinkedList<NotificationInfoBean>()

    private fun getNotificationInfoBeanList() {

        try {
            val gson = Gson()
            val type = object : TypeToken<List<NotificationInfoBean>>() {}.type
            val list = gson.fromJson<List<NotificationInfoBean>>("push_json_key", type)
            notificationQueue.addAll(list)
        } catch (e: Exception) {
        }
    }

    suspend fun nextNotificationInfoBean(): NotificationInfoBean? {

        if (notificationQueue.isEmpty()) {
            getNotificationInfoBeanList()
        }
        val bean = notificationQueue.poll()
        bean?.bitmap = downloadAndApplyRoundedCorners(bean.imageUrl)
        return bean
    }


    suspend fun downloadAndApplyRoundedCorners(url: String): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                val client = OkHttpClient()
                val request = Request.Builder().url(url).build()
                val response = client.newCall(request).execute()
                if (!response.isSuccessful) {
                    return@withContext null
                }
                val inputStream: InputStream = response.body()!!.byteStream()
                val bitmap = BitmapFactory.decodeStream(inputStream)
                val roundedBitmap = getRoundedCornersBitmap(bitmap, 8f)
                roundedBitmap
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }

    fun getRoundedCornersBitmap(source: Bitmap, radius: Float): Bitmap {
        val width = source.width
        val height = source.height

        val bitmap = createBitmap(width, height)
        val canvas = Canvas(bitmap)

        val paint = Paint().apply {
            isAntiAlias = true
            setShader(BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP))
        }

        val path = Path()
        val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
        path.addRoundRect(rect, radius, radius, Path.Direction.CW)
        path.close()

        canvas.drawPath(path, paint)
        return bitmap
    }

}