package com.base.scanqrclear.utils

import android.annotation.SuppressLint
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import kotlin.random.Random


object DateUtils {

    fun getDayOfWeek(timestamp: Long): String {
        val days = arrayOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
        val calendar = Calendar.getInstance().apply { timeInMillis = timestamp }
        return days[calendar.get(Calendar.DAY_OF_WEEK) - 1]
    }

    fun getYearFromTimestamp(timestamp: Long): Int {
        val calendar: Calendar = Calendar.getInstance()
        calendar.setTimeInMillis(timestamp)
        return calendar.get(Calendar.YEAR) // 返回年份
    }

    fun getMonthFromTimestamp(timestamp: Long): Int {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        return calendar[Calendar.MONTH] + 1 // 返回月份，需要加1因为Calendar.MONTH是从0开始的
    }

    fun getDayOfMonthFromTimestamp(timestamp: Long): Int {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        return calendar[Calendar.DAY_OF_MONTH] // 返回当前是月份的第几天
    }

    fun getDaySuffix(day: Int): String {
        return when (day) {
            1, 21, 31 -> "st"
            2, 22 -> "nd"
            3, 23 -> "rd"
            else -> "th"
        }
    }

    fun getHourOfDayFromTimestamp(timestamp: Long): Int {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        return calendar[Calendar.HOUR_OF_DAY] // 返回当前小时（24小时制）
    }

    fun getMinuteFromTimestamp(timestamp: Long): Int {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        return calendar[Calendar.MINUTE] // 返回当前分钟
    }


    /**
     * month是从1开的
     */
    fun getTimestampFromDateTime(year: Int, month: Int, day: Int, hour: Int, minute: Int): Long {
        val calendar = Calendar.getInstance()
        calendar[year, month - 1, day, hour] = minute
        return calendar.timeInMillis // 返回对应的时间戳
    }


    fun daysInMonth(year: Int, month: Int): Int {
        // 每个月的天数，二月默认为28天
        val monthDays = arrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

        // 检查是否是闰年
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            monthDays[1] = 29 // 如果是闰年，二月有29天
        }

        // 返回给定月份的天数
        return monthDays[month - 1]
    }

    @SuppressLint("SimpleDateFormat")
    fun generateRandomBirthdayTimestamp(age: Int): Long {
        val currentTimeMillis = System.currentTimeMillis()

        // 计算出生年份
        val birthYear = 2024 - age

        // 随机选择一个月份
        val randomMonth = Random.nextInt(12) + 1

        // 随机选择一个日期，确保是该月的有效日期
        val randomDay = Random.nextInt(28) + 1 // 简单起见，我们假设日期不会超过28

        // 构建出生日期字符串，包括时间部分
        val birthDate = "$birthYear-${randomMonth.toString().padStart(2, '0')}-${randomDay.toString().padStart(2, '0')} 00:00:00"

        // 将字符串转换为时间戳
        return try {
            // 尝试解析日期字符串
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            dateFormat.parse(birthDate)?.time ?: currentTimeMillis
        } catch (e: ParseException) {
            // 如果解析失败，返回当前时间戳
            currentTimeMillis
        }
    }

    fun calculateAge(birthTimestamp: Long): Int {
        // 创建一个 Calendar 实例
        val birthCalendar = Calendar.getInstance()
        // 设置时间戳对应的日期
        birthCalendar.timeInMillis = birthTimestamp

        // 创建一个 Calendar 实例用于获取当前日期
        val currentCalendar = Calendar.getInstance()

        // 计算年龄
        var age = currentCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR)

        // 如果当前日期还没有到生日，则年龄减一
        if (currentCalendar.get(Calendar.DAY_OF_YEAR) < birthCalendar.get(Calendar.DAY_OF_YEAR)) {
            age--
        }

        return age
    }


//    fun formatTimeAgo(timestamp: Long): String {
//        val instant = Instant.ofEpochMilli(timestamp)
//        val now = LocalDateTime.now(ZoneId.systemDefault())
//        val then = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
//
//        val seconds = ChronoUnit.SECONDS.between(then, now)
//        val minutes = ChronoUnit.MINUTES.between(then, now)
//        val hours = ChronoUnit.HOURS.between(then, now)
//        val days = ChronoUnit.DAYS.between(then, now)
//
//        return when {
//            days > 0 -> days.toString() + "day ago"
//            hours > 0 -> hours.toString() + "H ago"
//            minutes > 0 -> minutes.toString() + "Min ago"
//            else -> seconds.toString() + "s ago"
//        }
//    }

    fun formatTimeAgo(timestamp: Long): String {
        val then = Date(timestamp)
        val now = Date()
        val diff = now.time - then.time

        if (diff < 1000 * 60) {
            return (diff / 1000).toString() + " s ago"
        } else if (diff < 1000 * 60 * 60) {
            val minute = (diff / (1000 * 60))
            var string = " minute ago"
            if (minute > 1L) {
                string = " minutes ago"
            }
            return minute.toString() + string
        } else if (diff < 1000 * 60 * 60 * 24) {
            val hour = (diff / (1000 * 60 * 60))
            var string = " hour ago"
            if (hour > 1) {
                string = " hours ago"
            }
            return hour.toString() + string
        } else {
            val day = (diff / (1000 * 60 * 60 * 24))
            var string = " day ago"
            if (day > 1) {
                string = " days ago"
            }
            return day.toString() + string
        }
    }

}