package com.aiosman.ravenow.exp

import android.content.Context
import android.icu.text.SimpleDateFormat
import android.icu.util.Calendar
import com.aiosman.ravenow.R
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit

/**
 * 格式化时间为 xx 前
 */
fun Date.timeAgo(context: Context): String {
    val now = Date()
    val diffInMillis = now.time - this.time

    val seconds = diffInMillis / 1000
    val minutes = seconds / 60
    val hours = minutes / 60
    val days = hours / 24
    val years = days / 365

    return when {
        seconds < 60 -> context.getString(R.string.second_ago, seconds)
        minutes < 60 -> context.getString(R.string.minute_ago, minutes)
        hours < 24 -> context.getString(R.string.hour_ago, hours)
        days < 365 -> context.getString(R.string.days_ago, days)
        else -> SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(this)
    }
}

/**
 * 格式化时间为 xx-xx
 */
fun Date.formatPostTime(): String {
    val now = Calendar.getInstance()
    val calendar = Calendar.getInstance()
    calendar.time = this
    val year = calendar.get(Calendar.YEAR)
    var nowYear = now.get(Calendar.YEAR)
    val dateFormat = if (year == nowYear) {
        SimpleDateFormat("MM-dd", Locale.getDefault())
    } else {
        SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    }
    return dateFormat.format(this)
}

/**
 * yyyy-MM-dd HH:mm
 */
fun Date.formatPostTime2(): String {
    val calendar = Calendar.getInstance()
    calendar.time = this
    val year = calendar.get(Calendar.YEAR)
    val month = calendar.get(Calendar.MONTH) + 1
    val day = calendar.get(Calendar.DAY_OF_MONTH)
    val hour = calendar.get(Calendar.HOUR_OF_DAY)
    val minute = calendar.get(Calendar.MINUTE)
    
    // 确保两位数
    val monthStr = String.format("%02d", month)
    val dayStr = String.format("%02d", day)
    val hourStr = String.format("%02d", hour)
    val minuteStr = String.format("%02d", minute)
    
    return "$year-$monthStr-$dayStr $hourStr:$minuteStr"
}

fun Date.formatChatTime(context: Context): String {
    val now = Date()
    val diffInMillis = now.time - this.time

    val seconds = TimeUnit.MILLISECONDS.toSeconds(diffInMillis)
    val minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMillis)
    val hours = TimeUnit.MILLISECONDS.toHours(diffInMillis)
    val days = TimeUnit.MILLISECONDS.toDays(diffInMillis)
    val years = days / 365

    return when {
        seconds < 60 -> context.getString(R.string.seconds_ago, seconds)
        minutes < 60 -> context.getString(R.string.minutes_ago, minutes)
        hours < 24 -> SimpleDateFormat("HH:mm", Locale.getDefault()).format(this)
        days < 365 -> SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()).format(this)
        else -> SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(this)
    }
}