package com.kaixed.kchat.utils

import com.kaixed.kchat.utils.Utils.isChinese
import com.kaixed.kchat.utils.Utils.isEnglish
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType

/**
 * @Author: kaixed
 * @Date: 2024/11/2 14:30
 */
object Pinyin4jUtil {
    fun toPinyin(chineseText: String): String {
        val pinyinBuilder = StringBuilder()

        val format = HanyuPinyinOutputFormat()
        format.toneType = HanyuPinyinToneType.WITHOUT_TONE

        for (char in chineseText) {
            val pinyinArray = PinyinHelper.toHanyuPinyinStringArray(char, format)
            if (pinyinArray != null && pinyinArray.isNotEmpty()) {
                val pinyinWithoutTone = pinyinArray[0]
                pinyinBuilder.append(pinyinWithoutTone)
            } else {
                pinyinBuilder.append(char)
            }
        }
        return pinyinBuilder.toString()
    }

    fun compare(name1: String, name2: String): Int {
        val nickname1 = toPinyin(name1)
        val nickname2 = toPinyin(name2)
        if (nickname1 == nickname2) {
            return 0
        }
        if (!isEnglishOrChinese(nickname1[0].toString()) && isEnglishOrChinese(nickname2[0].toString())) {
            return 1
        }

        if (isEnglishOrChinese(nickname1[0].toString()) && !isEnglishOrChinese(nickname2[0].toString())) {
            return -1
        }
        return if (toPinyin(nickname1) > toPinyin(nickname2)) 1 else -1
    }

    private fun isEnglishOrChinese(str: String): Boolean {
        return isChinese(str) || isEnglish(str)
    }
}