package com.example.base.extensions

import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.annotation.ColorRes
import androidx.collection.ArrayMap
import androidx.core.content.ContextCompat
import com.example.base.utils.Utils
import java.lang.reflect.Field


/**
 * 对象转map
 */
fun Any.toMap(): ArrayMap<String, String> {
    val map: ArrayMap<String, String> = ArrayMap()

    val declaredFields: Array<Field> = this.javaClass.declaredFields
    for (field in declaredFields) {
        field.isAccessible = true
        val value = field.get(this) ?: continue
        map[field.name] = value.toString()
    }

    return map
}

/**
 * 获取颜色
 */
fun Any.getColor(@ColorRes resId: Int): Int {
    return ContextCompat.getColor(Utils.getApp(), resId)
}

/**
 * 全局toast
 */
fun Any.longToast(msg: CharSequence?) {
    if (msg == null) return
    val toast = Toast.makeText(Utils.getApp(), msg, Toast.LENGTH_LONG)
    toast.show()
}

/**
 * 全局toast
 */
fun Any.toast(msg: CharSequence?) {
    if (msg == null) return
    val toast = Toast.makeText(Utils.getApp(), msg, Toast.LENGTH_SHORT)
    toast.show()
}

fun Any.toast(msg: CharSequence?, isBack: Boolean) {
    if (msg == null) return
    val message = msg.split(",")
    if (message.isNotEmpty()) Toast.makeText(Utils.getApp(), message[0], Toast.LENGTH_SHORT).show()
}

private var mainThread: Handler? = null
fun Any.runOnUiThread(delayMillis: Long = 0L, action: () -> Unit) {
    if (mainThread == null) {
        mainThread = Handler(Looper.getMainLooper())
    }
    mainThread?.postDelayed({
        action.invoke()
    }, delayMillis)
}