package theorycrafter.ui.fiteditor

import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.runDesktopComposeUiTest
import eve.data.ModuleSlotType
import eve.data.ModuleType
import theorycrafter.*
import theorycrafter.TheorycrafterContext.eveData
import theorycrafter.TheorycrafterContext.fits
import theorycrafter.ui.fiteditor.FitEditorSlotKeys.AddOneItem
import theorycrafter.ui.fiteditor.FitEditorSlotKeys.RemoveOneItem
import kotlin.test.Test
import kotlin.test.assertEquals


/**
 * Tests fitting modules in the fit editor.
 */
@OptIn(ExperimentalTestApi::class)
class ModuleTest: TheorycrafterTest() {


    /**
     * Tests duplicating and subtracting an already fitted module (pressing plus/minus on a single-slot module).
     */
    @Test
    fun duplicateAndRemoveSameSingleModule() = runDesktopComposeUiTest {
        val fit = newFit(
            shipName = "Vexor",
            isValid = { it.fitting.slots.low.value >= 3 }
        )

        val gyro = eveData.moduleType("Gyrostabilizer I")
        fits.modifyAndSave {
            fit.fitModule(gyro, 0)
        }

        setApplicationContent {
            FitEditor(fit)
        }

        fun assertModuleType(moduleType: ModuleType?, lowSlotIndex: Int) {
            assertEquals(
                expected = moduleType,
                actual = fit.modules.inSlot(ModuleSlotType.LOW, lowSlotIndex)?.type
            )
        }

        assertModuleType(gyro, 0)

        onNode(Nodes.FitEditor.moduleRow(ModuleSlotType.LOW, 0)).apply {
            scrollToAndClick()

            press(AddOneItem)
            assertModuleType(gyro, 1)

            press(AddOneItem)
            assertModuleType(gyro, 2)

            press(RemoveOneItem)
            assertModuleType(null, 2)

            press(RemoveOneItem)
            assertModuleType(null, 1)
        }
    }


    /**
     * Test fitting a multimodule slot and then fitting a non-grouping module into it.
     */
    @Test
    fun replacingMultiModuleGroupWithNonGroupingModule() = runDesktopComposeUiTest {
        val fit = newFit(
            shipName = "Zealot",
            isValid = { it.fitting.turretHardpoints.total >= 3 }
        )

        val laser = eveData.moduleType("Heavy Pulse Laser II")
        val neut = eveData.moduleType("Small Energy Neutralizer II")
        fits.modifyAndSave {
            fit.fitModule(laser, 0)
            fit.fitModule(laser, 1)
            fit.fitModule(laser, 2)
        }

        setApplicationContent {
            FitEditor(fit)
        }
        onSubtreeRootedAt(Nodes.FitEditor.moduleRow(ModuleSlotType.HIGH, 0)).apply {
            hasText("3x", substring = true)
            hasText(laser.name, substring = true)
        }
        onNode(Nodes.FitEditor.moduleRow(ModuleSlotType.HIGH, 0)).apply {
            fitItemIntoSlot(neut.name)
        }

        assertEquals(neut, fit.modules.inSlot(ModuleSlotType.HIGH, 0)?.type)
    }


}