package com.example.myapplication.keyboard

import android.content.Context

class RecentStore(ctx: Context) {

    private val sp = ctx.getSharedPreferences("emoji_recent_store", Context.MODE_PRIVATE)

    private val keyEmoji = "recent_emoji"
    private val keyKaomoji = "recent_kaomoji"

    // 最近最多保存多少个（系统一般 30~50）
    private val maxSize = 40

    fun get(isEmoji: Boolean): List<String> {
        val key = if (isEmoji) keyEmoji else keyKaomoji
        val raw = sp.getString(key, "") ?: ""
        if (raw.isBlank()) return emptyList()
        // 用 \u0001 作为分隔，避免和颜文字里的空格/逗号冲突
        return raw.split('\u0001').filter { it.isNotBlank() }
    }

    fun push(item: String, isEmoji: Boolean) {
        if (item.isBlank()) return
        val key = if (isEmoji) keyEmoji else keyKaomoji

        val list = get(isEmoji).toMutableList()
        // 去重：把旧的删掉再插到最前
        list.removeAll { it == item }
        list.add(0, item)

        if (list.size > maxSize) {
            list.subList(maxSize, list.size).clear()
        }

        sp.edit().putString(key, list.joinToString(separator = "\u0001")).apply()
    }

    fun clear(isEmoji: Boolean) {
        val key = if (isEmoji) keyEmoji else keyKaomoji
        sp.edit().remove(key).apply()
    }
}
