package com.yidianling.ydlcommon.custom.player.notifycation

import android.annotation.SuppressLint
import android.app.Notification
import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.RemoteViews
import android.widget.TextView


import java.util.ArrayList

/**
 * 获取通知字体颜色
 * Created by zqk on 17-11-15.
 */

object NotificationHelper {
    private val NOTIFICATION_TITLE = "notification_title"
    val INVALID_COLOR = -1 // 无效颜色
    private var notificationTitleColor =
        INVALID_COLOR // 获取到的颜色缓存

    @SuppressLint("NewApi")
            /**
     * 获取系统通知栏主标题颜色，根据Activity继承自AppCompatActivity或FragmentActivity采取不同策略。
     *
     * @param context 上下文环境
     * @return 系统主标题颜色
     */
    fun getNotificationColor(context: Context): Int {
        try {
            if (notificationTitleColor == INVALID_COLOR) {
                if (context is AppCompatActivity) {
                    notificationTitleColor =
                        getNotificationColorCompat(
                            context
                        )
                } else {
                    notificationTitleColor =
                        getNotificationColorInternal(
                            context
                        )
                }
            }
        } catch (ignored: Exception) {
        }

        return notificationTitleColor
    }

    /**
     * 通过一个空的Notification拿到Notification.lceContentView，通过[RemoteViews.apply]方法返回通知栏消息根布局实例。
     *
     * @param context 上下文
     * @return 系统主标题颜色
     */
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    private fun getNotificationColorInternal(context: Context): Int {
        val builder = Notification.Builder(context)
        builder.setContentTitle(NOTIFICATION_TITLE)
        val notification = builder.build()
        try {
            val root = notification.contentView.apply(context, FrameLayout(context)) as ViewGroup
            val titleView = root.findViewById<View>(android.R.id.title) as TextView
            if (null == titleView) {
                iteratorView(
                    root,
                    object : Filter {
                        override fun filter(view: View) {
                            if (view is TextView) {
                                val textView = view as TextView
                                if (NOTIFICATION_TITLE == textView.text.toString()) {
                                    notificationTitleColor =
                                        textView.currentTextColor
                                }
                            }
                        }
                    })
                return notificationTitleColor
            } else {
                return titleView.currentTextColor
            }
        } catch (e: Exception) {
            return getNotificationColorCompat(
                context
            )
        }

    }

    /**
     * 使用getNotificationColorInternal()方法，Activity不能继承自AppCompatActivity（实测5.0以下机型可以，5.0及以上机型不行），
     * 大致的原因是默认通知布局文件中的ImageView（largeIcon和smallIcon）被替换成了AppCompatImageView，
     * 而在5.0及以上系统中，AppCompatImageView的setBackgroundResource(int)未被标记为RemotableViewMethod，导致apply时抛异常。
     *
     * @param context 上下文
     * @return 系统主标题颜色
     */
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    private fun getNotificationColorCompat(context: Context): Int {
        try {
            val builder = Notification.Builder(context)
            val notification = builder.build()
            val layoutId = notification.contentView.layoutId
            val root = LayoutInflater.from(context).inflate(layoutId, null) as ViewGroup
            val titleView = root.findViewById<View>(android.R.id.title) as TextView
            return titleView?.currentTextColor ?: getTitleColorIteratorCompat(
                root
            )
        } catch (e: Exception) {
        }

        return INVALID_COLOR
    }

    private fun iteratorView(view: View?, filter: Filter) {
        if (view == null || filter == null) {
            return
        }
        filter.filter(view)
        if (view is ViewGroup) {
            val viewGroup = view as ViewGroup?
            for (i in 0 until viewGroup!!.childCount) {
                val child = viewGroup.getChildAt(i)
                iteratorView(child, filter)
            }
        }
    }

    private fun getTitleColorIteratorCompat(view: View?): Int {
        if (view == null) {
            return INVALID_COLOR
        }
        val textViews = getAllTextViews(view)
        val maxTextSizeIndex =
            findMaxTextSizeIndex(textViews)
        return if (maxTextSizeIndex != Integer.MIN_VALUE) {
            textViews[maxTextSizeIndex].currentTextColor
        } else INVALID_COLOR
    }

    private fun findMaxTextSizeIndex(textViews: List<TextView>): Int {
        var max = Integer.MIN_VALUE.toFloat()
        var maxIndex = Integer.MIN_VALUE
        var index = 0
        for (textView in textViews) {
            if (max < textView.textSize) {
                // 找到字号最大的字体，默认把它设置为主标题字号大小
                max = textView.textSize
                maxIndex = index
            }
            index++
        }
        return maxIndex
    }

    /**
     * 实现遍历View树中的TextView，返回包含TextView的集合。
     *
     * @param root 根节点
     * @return 包含TextView的集合
     */
    private fun getAllTextViews(root: View): List<TextView> {
        val textViews = ArrayList<TextView>()
        iteratorView(
            root,
            object : Filter {
                override fun filter(view: View) {
                    if (view is TextView) {
                        textViews.add(view as TextView)
                    }
                }
            })
        return textViews
    }

    private interface Filter {
        fun filter(view: View)
    }
}
