package com.test.basd.smartjunkcleaner.helps

import android.view.View
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Locale

object KotlinExt {


    private val aesMap = mutableMapOf<Int, String>()

    fun Int.string(vararg arg: Any) = try {
        (aesMap[this] ?: BaseApplication.context.getString(this).decode()).run {
            aesMap[this@string] = this
            String.format(this, *arg)
        }
    } catch (_: Exception) {
        ""
    }

    fun String.decode() = AESHelper.decrypt(this)
        .replace("\\r", "\r")
        .replace("\\n", "\n")
        .replace("\\'", "'")
        .replace("\\\"", "\"")
        .replace("\\?", "?")
        .replace("&amp;", "&")

    fun Collection<View>.setOnClickListener(listener: (View) -> Unit) {
        this.forEach {
            it.setOnClickListener(listener)
        }
    }

    fun View.setTrackedOnClickListener(action: (view: View) -> Unit) {
        setOnClickListener {
            action(this)

            var view: View? = this
            while (view != null) {
                try {
                    val obj = JSONObject()
                    obj.put("view_id", resources.getResourceEntryName(view.id))
                    EventHelper.event("click_id", ext = obj)
                    break
                } catch (_: Exception) {
                    view = view.parent as? View
                }
            }
        }
    }

    fun Number.toFormatSize(count: Int = 1): String {
        var suffix = "B"
        var fSize = this.toDouble()
        if (fSize > 1024) {
            suffix = "KB"
            fSize /= 1024.0
        }
        if (fSize > 1024) {
            suffix = "MB"
            fSize /= 1024.0
        }
        if (fSize > 1024) {
            suffix = "GB"
            fSize /= 1024.0
        }
        return String.format("%.${count}f %s", fSize, suffix)
    }

    fun Long.toFormatTime(): String {
        return SimpleDateFormat("MMM/dd/yyyy", Locale.getDefault()).format(this)
    }
}