package com.gh.gamecenter.common.utils

import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.provider.CalendarContract
import java.util.*


/**
 * 日历事件 工具类
 */
object CalendarEventUtils {

    // 添加日历事件
    fun addCalendarEvent(event: CalendarEvent, context: Context): Long? {
        val calendarId = getDefaultCalendarId(context)
        if (calendarId == -1L) return null

        val isExists = checkEventExistsStrict(calendarId, event, context)
        if (isExists) {
            return 0
        }

        val startTime = event.startTime
        val endTime = event.endTIme
        val values = ContentValues().apply {
            put(CalendarContract.Events.CALENDAR_ID, calendarId)
            put(CalendarContract.Events.TITLE, event.title)
            put(CalendarContract.Events.DESCRIPTION, event.remark)
            put(CalendarContract.Events.DTSTART, startTime)
            put(CalendarContract.Events.DTEND, endTime)
            put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id)

            // 可选属性
            put(CalendarContract.Events.HAS_ALARM, 1) // 是否需要提醒
        }

        try {
            val uri = context.contentResolver.insert(
                CalendarContract.Events.CONTENT_URI,
                values
            )

            val eventId = ContentUris.parseId(uri!!)
            // 添加提醒
            addEventReminder(eventId, event.reminderTime, context)
            return eventId
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    // 添加事件提醒
    private fun addEventReminder(eventId: Long, reminderTime: Long, context: Context) {
        val reminderMinutes = reminderTime / (1000 * 60)
        val values = ContentValues().apply {
            put(CalendarContract.Reminders.EVENT_ID, eventId)
            put(CalendarContract.Reminders.MINUTES, reminderMinutes)
            put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_DEFAULT)
        }

        try {
            context.contentResolver.insert(
                CalendarContract.Reminders.CONTENT_URI,
                values
            )
        } catch (_: Exception) {
        }
    }

    private fun getDefaultCalendarId(context: Context): Long {
        var calendarId: Long = -1
        val projection = arrayOf(
            CalendarContract.Calendars._ID,
            CalendarContract.Calendars.CALENDAR_DISPLAY_NAME
        )

        context.contentResolver.query(
            CalendarContract.Calendars.CONTENT_URI, projection, null, null, null
        )?.use { cursor ->
            if (cursor.moveToFirst()) {
                val index = cursor.getColumnIndex(CalendarContract.Calendars._ID)
                if (index >= 0) {
                    calendarId = cursor.getLong(index)
                }

            }
        }

        return calendarId
    }

    private fun checkEventExistsStrict(
        calendarId: Long,
        event: CalendarEvent,
        context: Context
    ): Boolean {
        try {
            val projection = arrayOf(
                CalendarContract.Events._ID,
                CalendarContract.Events.TITLE,
                CalendarContract.Events.DESCRIPTION,
                CalendarContract.Events.DTSTART,
                CalendarContract.Events.DTEND,
                CalendarContract.Events.CALENDAR_ID
            )

            val selectionParts = mutableListOf<String>()
            val selectionArgs = mutableListOf<String>()

            // 添加必需的条件
            selectionParts.add("${CalendarContract.Events.CALENDAR_ID} = ?")
            selectionArgs.add(calendarId.toString())

            selectionParts.add("${CalendarContract.Events.TITLE} = ?")
            selectionArgs.add(event.title)

            selectionParts.add("${CalendarContract.Events.DTSTART} = ?")
            selectionArgs.add("${event.startTime}")

            selectionParts.add("${CalendarContract.Events.DTEND} = ?")
            selectionArgs.add("${event.endTIme}")

            // 添加可选条件
            selectionParts.add("${CalendarContract.Events.DESCRIPTION} = ?")
            selectionArgs.add(event.remark)

            val selection = selectionParts.joinToString(" AND ")

            context.contentResolver.query(
                CalendarContract.Events.CONTENT_URI,
                projection,
                selection,
                selectionArgs.toTypedArray(),
                null
            )?.use { cursor ->
                return cursor.count > 0
            }
        } catch (_: Exception) {

        }
        return false
    }

    data class CalendarEvent(
        val title: String,
        val startTime: Long, // 单位 ms
        val endTIme: Long,  // 单位 ms
        val reminderTime: Long, // 单位 ms
        val remark: String
    )
}