package click.kamil.maven.core;

import click.kamil.maven.api.JmsOrderListener;
import click.kamil.maven.api.MavenOrderApi;
import click.kamil.maven.base.AbstractMavenStateMachine;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

@Configuration
@EnableStateMachineFactory
public class MavenOrderStateMachine extends AbstractMavenStateMachine {

    @Override
    public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
        transitions
            .withExternal()
                .source("INIT").target("BUSY")
                .event("SUBMIT")
                .action(loggingAction())
            .and()
            .withExternal()
                .source("BUSY").target("DONE")
                .event("ORDER_EVENT");
    }

    @RestController
    @RequiredArgsConstructor
    public static class OrderController implements MavenOrderApi {
        private final StateMachineFactory<String, String> factory;

        @Override
        public void submitOrder(String orderId) {
            StateMachine<String, String> sm = factory.getStateMachine(orderId);
            sm.sendEvent("SUBMIT");
        }
    }

    @Service
    @RequiredArgsConstructor
    public static class OrderService implements JmsOrderListener {
        private final StateMachineFactory<String, String> factory;

        @Override
        public void onMessage(String message) {
            StateMachine<String, String> sm = factory.getStateMachine();
            sm.sendEvent("ORDER_EVENT");
        }
    }
}
