package theorycrafter.ui.fiteditor

import androidx.compose.ui.test.hasText
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.
 */
class ModuleTest: TheorycrafterTest() {


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

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

        rule.setApplicationContent {
            FitEditor(fit)
        }

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

        assertModuleType(gyro, 0)

        rule.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() = runBlockingTest {
        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)
        }

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

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


}