# State Script

### Features

* **Automatic state machine setup** - No manual configuration required
* **Enum-based state management** - Uses `StateEnum` interface (no class instantiation required)
* **Simple state switching** - Works directly with enum values and descriptions
* **State iteration** - Automatic state switching in the backend
* **Skip conditions** - Conditional state skipping support
* **Runtime updates** - Change skip conditions at runtime

### Usage

```kotlin
import net.botwithus.kxapi.game.skilling.production.ui.impl.smithing.SmithingProduction
import net.botwithus.kxapi.game.skilling.skilling
import net.botwithus.kxapi.permissive.StateEnum
import net.botwithus.kxapi.script.StateScript
import net.botwithus.scripts.Info
import net.botwithus.xapi.query.SceneObjectQuery

enum class TestState : StateEnum {
    OPEN("Open"),
    PROGRESS("Progress"),
    FINISHED("Finished");

    override val description: String

    constructor(desc: String) {
        description = desc
    }
}

@Info(name = "TestingScript", description = "For Testing", version = "1.0.0", author = "Mark")
class TestScript : StateScript<TestState>() {


    override fun getSkipConditions(): Map<BotState, () -> Boolean> = mapOf(
        BotState.GATHERING to { false },
        BotState.SKILLING to { false }
    )

    val product = skilling.productionOf<SmithingProduction> {
        input("Mithril ore")
        output("Mithril bar")
    }

    override suspend fun onTick() {
        val currentState = getStateIterator()?.getCurrentState()
        when (currentState) {
            TestState.OPEN -> handleOpen()
            TestState.PROGRESS -> handleProgress()
            TestState.FINISHED -> handleFinished()
            null -> {
                println("No current state - setting to OPEN")
                setState(TestState.OPEN)
            }
        }
    }

    private suspend fun handleOpen() {
        println("Opening smithing interface...")
        SceneObjectQuery().name("Furnace").option("Smelt").results().nearest().interact()

        // Wait a bit for the interface to open, then move to next state
        awaitTicks(3)
        nextState()
    }

    private suspend fun handleProgress() {
        product.produceItem(
            onProgress = { message, prog1, prog2, prog3, xp ->
                this.println("${message.message}, ${prog1}, ${prog2}, ${prog3}, ${xp}")
            },
            onFinished = {
                println("FINISHED")
                nextState()
            }
        )
    }

    private suspend fun handleFinished() {
        println("Production completed!")
        resetStateIterator()
    }
}
```

### Constructor Options

```kotlin
// Enable debug mode (recommended for development)
class MyScript : StateScript<BotState>(debug = true)

// Disable debug mode (for production)
class MyScript : StateScript<BotState>(debug = false)

// Use custom state list with debug enabled
class MyScript : StateScript<BotState>(
    debug = true,
    states = listOf(BotState.IDLE, BotState.GATHERING, BotState.BANKING)
)
```

#### Debug Parameter

The `debug` parameter controls verbose logging and debugging output:

* **`debug = true`** - Enables detailed logging, state transitions, and debugging information
* **`debug = false`** - Minimal logging, suitable for production use

When debug mode is enabled, you'll see additional console output including:

* State transitions
* Iterator operations
* Skip condition evaluations
* Detailed error messages

### When to Use

Use StateScript when:

* You want automatic state machine functionality
* You need simple enum-based state management (no class instantiation)
* You want the most automated approach
* You have complex state transitions
* You prefer working with enum values directly rather than state classes

### Key Methods

* `getSkipConditions()` - Override to set initial skip conditions
* `updateSkipConditions()` - Change skip conditions at runtime
* `getStateIterator()` - Get the current state iterator
* `nextState()` - Move to the next state
* `resetStateIterator()` - Reset to the first state
* `setState(state)` - Set a specific state


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kxapi.gitbook.io/kxapi/scripting/script-types/state-script.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
