/*
 *   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 java.util.*

object IgnoreSystemTable : CompositeIdTable("IgnoredPlayers") {
    val ignorer = reference("Ignorer", SteamwarUserTable).index()
    val ignored = reference("Ignored", SteamwarUserTable).index()

    override val primaryKey = PrimaryKey(ignorer, ignored)

    init {
        addIdColumn(ignorer)
        addIdColumn(ignored)
    }
}

class IgnoreSystem(id: EntityID<CompositeID>) : CompositeEntity(id) {
    var ignorer by IgnoreSystemTable.ignorer
    var ignored by IgnoreSystemTable.ignored

    companion object : CompositeEntityClass<IgnoreSystem>(IgnoreSystemTable) {
        @JvmStatic
        fun isIgnored(ignorer: UUID, ignored: UUID) =
            useDb { isIgnored(SteamwarUser.get(ignorer)!!, SteamwarUser.get(ignored)!!) }

        @JvmStatic
        fun isIgnored(ignorer: SteamwarUser, ignored: SteamwarUser) =
            useDb {
                find {
                    (IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id)
                }.firstOrNull() != null
            }

        @JvmStatic
        fun ignore(ignorer: SteamwarUser, ignored: SteamwarUser) =
            useDb {
                new {
                    this.ignorer = ignorer.id
                    this.ignored = ignored.id
                }
            }

        @JvmStatic
        fun unIgnore(ignorer: SteamwarUser, ignored: SteamwarUser) =
            useDb {
                find {
                    (IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id)
                }.firstOrNull()?.delete()
            }
    }
}