package com.ffii.fpsms.modules.stock.trace

import org.springframework.stereotype.Component
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Component
open class TraceSqlSupport {
    val dateFmt: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE
    val dateTimeFmt: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

    open fun str(v: Any?): String = v?.toString()?.trim() ?: ""

    open fun strOrNull(v: Any?): String? = v?.toString()?.trim()?.ifBlank { null }

    open fun longVal(v: Any?): Long? = when (v) {
        null -> null
        is Number -> v.toLong()
        else -> v.toString().toLongOrNull()
    }

    open fun intVal(v: Any?): Int? = when (v) {
        null -> null
        is Number -> v.toInt()
        else -> v.toString().toIntOrNull()
    }

    open fun decimal(v: Any?): BigDecimal = when (v) {
        null -> BigDecimal.ZERO
        is BigDecimal -> v
        is Number -> BigDecimal.valueOf(v.toDouble())
        else -> v.toString().toBigDecimalOrNull() ?: BigDecimal.ZERO
    }

    open fun decimalOrNull(v: Any?): BigDecimal? = when (v) {
        null -> null
        is BigDecimal -> v
        is Number -> BigDecimal.valueOf(v.toDouble())
        else -> v.toString().toBigDecimalOrNull()
    }

    open fun formatDate(v: Any?): String? = when (v) {
        null -> null
        is LocalDate -> v.format(dateFmt)
        is java.sql.Date -> v.toLocalDate().format(dateFmt)
        is LocalDateTime -> v.toLocalDate().format(dateFmt)
        is java.sql.Timestamp -> v.toLocalDateTime().toLocalDate().format(dateFmt)
        else -> v.toString().takeIf { it.isNotBlank() }
    }

    open fun formatDateTime(v: Any?): String? = when (v) {
        null -> null
        is LocalDateTime -> v.format(dateTimeFmt)
        is java.sql.Timestamp -> v.toLocalDateTime().format(dateTimeFmt)
        is LocalDate -> v.atStartOfDay().format(dateTimeFmt)
        is java.sql.Date -> v.toLocalDate().atStartOfDay().format(dateTimeFmt)
        else -> v.toString().takeIf { it.isNotBlank() }
    }
}
