package com.dowstats.data.entities

import com.dowstats.data.dto.controllers.ModifierDto
import com.dowstats.data.rgd.RgdData
import com.dowstats.data.rgd.RgdDataUtil.getBooleanByName
import com.dowstats.data.rgd.RgdDataUtil.getDoubleByName
import com.dowstats.data.rgd.RgdDataUtil.getPureIntByName
import com.dowstats.data.rgd.RgdDataUtil.getRgdTableByName
import com.dowstats.data.rgd.RgdDataUtil.getStringByName
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.MappedSuperclass

@MappedSuperclass
open class ModifiersBase {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null

    var reference: String? = null
    var target: String? = null
    var usageType: String? = null
    var value: Double? = null
    var applicationType: String? = null
    var probabilityOfApplying: Double? = null
    var exclusive: Boolean? = null

    fun toDto(): ModifierDto {
        return ModifierDto(
            id = id!!,
            reference = reference,
            usageType = usageType,
            value = value,
            target = target,
            applicationType = applicationType,
            probabilityOfApplying = probabilityOfApplying,
            exclusive = exclusive
        )
    }

    companion object ModifiersBaseCompanion {

        fun <T : ModifiersBase> List<T>.filterUseless(): List<T> =
            this.filterNot {
                it.usageType == "type_modifierusagetype\\tp_mod_usage_addition.lua" && it.value == 0.0 ||
                        it.usageType == "type_modifierusagetype\\tp_mod_usage_multiplication.lua" && it.value == 1.0
            }

        fun <T : ModifiersBase> T.fillDataFromRgdTable(rgdData: List<RgdData>): T {
            this.reference = rgdData.getStringByName("\$REF")
            this.target = rgdData.getStringByName("target_type_name")
            this.usageType = rgdData.getRgdTableByName("usage_type")?.getStringByName("\$REF")
            this.value = try{ rgdData.getDoubleByName("value") } catch (e: Exception) { null }
            this.applicationType = rgdData.getRgdTableByName("application_type")?.getStringByName("\$REF")
            this.exclusive = try { rgdData.getBooleanByName("exclusive") } catch (e: Exception) { false }
            this.probabilityOfApplying = try { rgdData.getDoubleByName("probability_of_applying") } catch (e: Exception) {
                rgdData.getPureIntByName("probability_of_applying")?.toDouble()
            }
            return this
        }
    }
}

