package com.base.scanqrclear.bean

import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.TimeZone

//BEGIN:VEVENT

//SUMMARY:xxx
//DTSTART:20241230T072300
//DTEND:20241231T072300
//LOCATION:xxxx
//DESCRIPTION:xxxx

//END:VEVENT

data class EventUIBean(
    var summary: String = "",
    var dtstart: String = "",
    var dtend: String = "",
    var location: String = "",
    var description: String = ""
) : ScanBean(FunctionUIBean.KEY_EVENT) {

    var startTime: Long = 0
    var endTime: Long = 0

    companion object {

        fun isEventQR(qr: String): Boolean {

            if (qr.startsWith("BEGIN:VEVENT") && qr.endsWith("END:VEVENT")) {
                return true
            }
            return false
        }

        fun createEventQRString(bean: EventUIBean): String {
            val sb = StringBuilder()
            val start = "BEGIN:VEVENT"
            sb.append(start).append("\n")
            sb.append("SUMMARY:").append(bean.summary).append("\n")
            sb.append("DTSTART:").append(bean.dtstart).append("\n")
            sb.append("DTEND:").append(bean.dtend).append("\n")
            sb.append("LOCATION:").append(bean.location).append("\n")
            sb.append("DESCRIPTION:").append(bean.description).append("\n")
            val end = "END:VEVENT"
            sb.append(end)
            return sb.toString()
        }

        //        DTSTART:20250102T060100
//        DTEND:20250103T060100
        @SuppressLint("SimpleDateFormat")
        fun createEventBean(qr: String): EventUIBean {
            val eventUIBean = EventUIBean()
            val kvList = qr.split("\n")
            kvList.forEach {
                val pair = it.split(":")
                val key = pair[0]
                val value = pair[1]
                if (key == "SUMMARY") {
                    eventUIBean.summary = value
                }
                if (key == "DTSTART") {
                    eventUIBean.dtstart = value
                }
                if (key == "DTEND") {
                    eventUIBean.dtend = value
                }
                if (key == "LOCATION") {
                    eventUIBean.location = value
                }
                if (key == "DESCRIPTION") {
                    eventUIBean.description = value
                }
            }
            val format = SimpleDateFormat("yyyyMMdd'T'HHmmss")
            format.timeZone = TimeZone.getTimeZone("UTC")
            eventUIBean.startTime = format.parse(eventUIBean.dtstart)?.time ?: 0
            eventUIBean.endTime = format.parse(eventUIBean.dtend)?.time ?: 0
            return eventUIBean
        }
    }
}
