/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.sql

import de.steamwar.sql.internal.useDb
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.dao.id.CompositeID
import org.jetbrains.exposed.v1.core.dao.id.CompositeIdTable
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.dao.CompositeEntity
import org.jetbrains.exposed.v1.dao.CompositeEntityClass
import org.jetbrains.exposed.v1.jdbc.insertIgnore

object SchemEloTable: CompositeIdTable("SchemElo") {
    val schemId = reference("SchemId", SchematicNodeTable)
    val season = integer("Season").entityId()
    val elo = integer("Elo")

    override val primaryKey = PrimaryKey(schemId, season)

    init {
        addIdColumn(schemId)
    }
}

class SchemElo(id: EntityID<CompositeID>): CompositeEntity(id) {
    companion object: CompositeEntityClass<SchemElo>(SchemEloTable) {
        @JvmStatic
        fun getElo(node: SchematicNode, season: Int, defaultElo: Int = 0) = useDb {
            find { (SchemEloTable.schemId eq node.id) and (SchemEloTable.season eq season) }.firstOrNull()?.elo ?: defaultElo
        }

        @JvmStatic
        fun getCurrentElo(schemId: Int) = getElo(SchematicNode.byId(schemId)!!, Season.getSeason())

        @JvmStatic
        fun setElo(node: Int, elo: Int) = useDb {
            findByIdAndUpdate(CompositeID {
                it[SchemEloTable.schemId] = node
                it[SchemEloTable.season] = Season.getSeason()
            }) {
                it.elo = elo
            } ?: SchemEloTable.insertIgnore {
                it[SchemEloTable.schemId] = node
                it[SchemEloTable.season] = Season.getSeason()
                it[SchemEloTable.elo] = elo
            }

            return@useDb
        }
    }

    var node by SchemEloTable.schemId
    var season by SchemEloTable.season
    var elo by SchemEloTable.elo
}