package com.isidroid.utils

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import java.io.Serializable

private val debugGson = GsonBuilder()
    .setPrettyPrinting()
    .create()

val Bundle?.debug: String?
    get() {
        this ?: return null
        return keySet().joinToString(", ") { "$it=${get(it)}" }
    }

inline fun <T> tryCatch(block: () -> T): T? = try {
    block()
} catch (t: Throwable) {
    null
}

val Any?.json: String
    get() = debugGson.toJson(this)

inline fun <reified T> Gson.fromJson(json: String?): T = fromJson(json, object : TypeToken<T>() {}.type)
inline fun <reified T> Gson.fromJson(obj: JsonObject): T? = fromJson(obj, object : TypeToken<T>() {}.type)
inline fun <reified T> Any.isType(): Boolean = this is T


inline fun <reified T : Parcelable> Bundle.getParcelableCompat(key: String, clazz: Class<T>): T? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        getParcelable(key, clazz)
    else
        getParcelable(key)
}

inline fun <reified T : Serializable> Bundle.getSerializableCompat(key: String, clazz: Class<T>): T? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        getSerializable(key, clazz)
    else
        getSerializable(key) as? T
}

inline fun <reified T : Parcelable> Bundle.getParcelableListCompat(key: String, clazz: Class<T>): ArrayList<T>? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        getParcelableArrayList(key, clazz)
    else
        getParcelableArrayList(key)
}