package com.aiosman.ravenow.utils

import android.content.Context
import android.content.SharedPreferences
import com.aiosman.ravenow.ui.post.Draft
import com.aiosman.ravenow.ui.post.DraftImageItem
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 草稿存储管理器
 * - 仅保存最近5条草稿
 * - 新草稿加入时自动淘汰最旧的一条
 */
class DraftStore(context: Context) {
    private val prefs: SharedPreferences =
        context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

    data class DraftEntity(
        val textContent: String,
        val imageList: List<DraftImageItem>,
        val createdAt: Long
    ) {
        fun toDraft(): Draft {
            return Draft(textContent, imageList, createdAt)
        }
    }

    fun getAllDrafts(): List<Draft> {
        val json = prefs.getString(KEY_DRAFTS, "[]") ?: "[]"
        return runCatching {
            val type = object : TypeToken<List<DraftEntity>>() {}.type
            val entities = gson.fromJson<List<DraftEntity>>(json, type) ?: emptyList()
            entities.sortedByDescending { it.createdAt }.map { it.toDraft() }
        }.getOrDefault(emptyList())
    }

    fun saveDraft(draft: Draft) {
        // 如果文字和图片都为空，不保存
        if (draft.textContent.isBlank() && draft.imageList.isEmpty()) {
            return
        }

        val current = getAllDrafts().map { draftToEntity(it) }.toMutableList()
        
        // 添加新草稿到最前面
        current.add(0, draftToEntity(draft))
        
        // 只保留最近5条
        while (current.size > MAX_SIZE) {
            current.removeAt(current.lastIndex)
        }
        
        save(current)
    }

    fun deleteDraft(index: Int) {
        val current = getAllDrafts().map { draftToEntity(it) }.toMutableList()
        if (index >= 0 && index < current.size) {
            current.removeAt(index)
            save(current)
        }
    }

    fun clearAll() {
        save(emptyList())
    }

    private fun draftToEntity(draft: Draft): DraftEntity {
        return DraftEntity(
            textContent = draft.textContent,
            imageList = draft.imageList,
            createdAt = draft.createdAt
        )
    }

    private fun save(list: List<DraftEntity>) {
        prefs.edit().putString(KEY_DRAFTS, gson.toJson(list)).apply()
    }

    companion object {
        private const val PREF_NAME = "draft_store_pref"
        private const val KEY_DRAFTS = "drafts_v1"
        private const val MAX_SIZE = 5
    }
}

