package es.verdnatura.domain

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.text.Html
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import java.text.SimpleDateFormat
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale

fun List<Any?>.formatWithQuotes(): String {
    return "[" + joinToString(", ") { if (it is String) "\"$it\"" else it.toString() } + "]"
}

@RequiresApi(Build.VERSION_CODES.N)
fun Any.toast(
    context: Context?,
    duration: Int = Toast.LENGTH_SHORT,
    color: Int = Color.WHITE
): Toast {
    val toast = Toast.makeText(
        context,
        Html.fromHtml("<font color='$color' ><b>$this</b></font>", 0),
        duration
    )
    //toast2.setGravity(Gravity.TOP, 0, 0)
    toast.show()
    return toast.apply { show() }
}

fun <T : Any> T?.notNull(f: (it: T) -> Unit) {
    if (this != null) f(this)
}

fun EditText.toInt(): Int {
    return this.text.toString().toInt()
}

fun EditText.toLong(): Long {
    return this.text.toString().toLong()
}

fun toDateString(date: Date): String {
    val format = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
    return format.format(date)
}

@RequiresApi(Build.VERSION_CODES.O)
fun String?.isoToString(returnOnlyDate: Boolean = false): String {

    return if (!this.isNullOrEmpty() && this!!.contains("T")) {
        val utcZonedDateTime = ZonedDateTime.parse(this, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
        val myDate = utcZonedDateTime.withZoneSameInstant(ZonedDateTime.now().zone)
            .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
        if (returnOnlyDate) {
            (myDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"))).replace("T", " ")
                .substring(0, 10)
        } else {
            (myDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"))).replace("T", " ")
        }
    } else if (!this.isNullOrEmpty() && !this!!.contains("T")) {
        this
    } else {
        ""
    }
}
