package com.ffii.fpsms.modules.common

import java.time.LocalDate
import java.time.format.DateTimeFormatter

object CodeGenerator {
    // Old Function
    private var dateFormat = DateTimeFormatter.ofPattern("yyMMdd")
    fun generateCode(prefix: String, itemId: Long, count: Int): String {
        // prefix = "ITEM" || "LOT"
        // count = number of record from db
        val todayStr = LocalDate.now().format(dateFormat)
        val itemStr = String.format("%04d", itemId)
        val countStr = String.format("%04d", count)
        return "$prefix-$todayStr$itemStr$countStr"
    }

    // Default Value for Order No & Lot No.
    val DEFAULT_SUFFIX_FORMAT = "%04d";
    val DEFAULT_PATTERN = "yyyyMMdd";
    val DEFAULT_FORMATTER = DateTimeFormatter.ofPattern(DEFAULT_PATTERN)
    val DEFAULT_MIDFIX = LocalDate.now().format(DEFAULT_FORMATTER)
    fun generateNo(
        suffixFormat: String? = null,
        pattern: String? = null,
        prefix: String,
        midfix: String? = null,
        latestCode: String?
    ): String {
        val formatter = pattern?.let { DateTimeFormatter.ofPattern(it) } ?: DEFAULT_FORMATTER
        val finalSuffixFormat = suffixFormat ?: DEFAULT_SUFFIX_FORMAT

        val midfix = midfix ?: LocalDate.now().format(formatter)
        val suffix = String.format(finalSuffixFormat, 1)

        if (latestCode != null) {
            val splitLatestCode = latestCode.split("-")
            if (splitLatestCode.size > 2) {
                val latestNo = splitLatestCode[2].toInt()
                return listOf<String>(prefix, midfix, String.format(finalSuffixFormat, latestNo + 1)).joinToString("-")
            }
        }

        return listOf<String>(prefix, midfix, suffix).joinToString("-")
    }
}