package com.gh.gamecenter.common.entity

import com.gh.gamecenter.common.utils.roundTo
import com.google.gson.annotations.SerializedName

data class PKEntity(
    @SerializedName("_id")
    val id: String = "",
    val title: String = "",
    val option1: PKOption = PKOption(),
    val option2: PKOption = PKOption(),
    @SerializedName("show_result")
    val showResult: Boolean = false, // 投票结束后投票结果是否向未参与者开放
    @SerializedName("is_join")
    var isJoin: Boolean = false, // 当前设备/用户是否已参与投票
    @SerializedName("user_option")
    var userOption: String = "", // is_join=true时，当前用户/设备所投票的选项
    val link: LinkEntity? = null,
    val time: Time = Time()
) {
    data class PKOption(
        val text: String = "",
        var num: Int = 0,
    )

    data class Time(
        val start: Long = 0L, // pk开始时间
        val end: Long = 0L, // pk结束时间
    )

    // 是否已结束
    val isExpired: Boolean
        get() = System.currentTimeMillis() >= time.end * 1000L

    val shouldShowResult: Boolean
        get() = (isJoin || (isExpired && showResult)) && (option1.num != 0 || option2.num != 0)

    // 参加人数
    val totalNum: Int
        get() = option1.num + option2.num

    val progress: Float
        get() = when {
            totalNum == 0 -> 0F
            option1.num != 0 && option2.num != 0 -> (option1.num / totalNum.toFloat()).roundTo(3)
                .coerceIn(0.001F, 0.999F) // 百分比最小0.1%，最大99.9%
            else -> option1.num / totalNum.toFloat()
        }

    val isVotePositive
        get() = isJoin && userOption == "option1"

    val isVoteNegative
        get() = isJoin && userOption == "option2"

    val positiveResultText: String
        get() = if (isVotePositive) "${option1.text}(已投票)" else option1.text

    val negativeResultText: String
        get() = if (isVoteNegative) "(已投票)${option2.text}" else option2.text
}