package theorycrafter.tournaments

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.window.WindowPosition
import eve.data.ShipType
import theorycrafter.LocalTheorycrafterWindowManager
import theorycrafter.SimpleSavedWindowState
import theorycrafter.TheorycrafterWindow
import theorycrafter.rememberWindowStateAndUpdateSettings
import theorycrafter.sharedapp.generated.resources.Res
import theorycrafter.sharedapp.generated.resources.doctrine
import theorycrafter.tournaments.TournamentRules.CompositionRules
import theorycrafter.ui.TheorycrafterTheme
import theorycrafter.ui.tournaments.TournamentWindowContent


/**
 * The doctrines window.
 */
@Composable
fun DoctrinesWindow() {
    val windowManager = LocalTheorycrafterWindowManager.current
    val state = windowManager.doctrinesWindowState
    if (state !is SimpleSavedWindowState.Open)
        return

    val windowState = rememberWindowStateAndUpdateSettings(
        windowSettings = state.windowSettings,
        defaultPosition = { WindowPosition.PlatformDefault },
        defaultSize = { TheorycrafterTheme.sizes.doctrinesWindowDefaultSize },
    )

    TheorycrafterWindow(
        title = "Doctrines",
        onCloseRequest = windowManager::closeDoctrinesWindow,
        state = windowState
    ) {
        TournamentWindowContent(DoctrinesTournamentDescriptor)

        LaunchedEffect(state, window) {
            state.window = window
        }
    }
}


/**
 * The [TournamentDescriptor] for the doctrines window.
 */
private val DoctrinesTournamentDescriptor = TournamentDescriptor(
    id = "doctrines",
    name = "Doctrines",
    shortName = "Doctrines",
    icon = Res.drawable.doctrine,
    suggestedFitTag = null,
    compositionsWindowTitle = "Doctrines",
    rulesFactory = { DoctrineRules },
)


/**
 * The fale [TournamentRules] for the "doctrines tournament".
 */
private val DoctrineRules = TournamentRules(
    compositionRules = DoctrineCompositionRules,
    fittingRules = EverythingIsAllowed
)


/**
 * Returns whether the given tournament is the "doctrines tournament".
 */
val Tournament.isDoctrines: Boolean
    get() = rules == DoctrineRules


/**
 * Returns whether the given composition is a doctrine.
 */
val Composition.isDoctrine: Boolean
    get() = tournament.isDoctrines


/**
 * The [CompositionRules] for the "doctrines tournament".
 */
data object DoctrineCompositionRules: CompositionRules {

    override fun isShipLegal(shipType: ShipType) = true

    override fun shipsCost(shipTypes: List<ShipType?>) = error("Doctrine rules have no ship costs")

    override fun compositionShipsIllegalityReason(composition: Composition) = List(composition.size) { null }

    override fun compositionIconShipTypes(composition: Composition): List<ShipType?> {
        // Most common ship type
        return listOf(composition.ships.maxByOrNull { it?.amountOrOne ?: 0 }?.shipType)
    }

}


