package com.friday.distributor.statemachine;

import com.friday.distributor.constant.Events.*;
import com.friday.distributor.constant.States.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.persist.RepositoryStateMachinePersist;
import org.springframework.statemachine.redis.RedisStateMachineContextRepository;
import org.springframework.statemachine.redis.RedisStateMachinePersister;

@Configuration
public class StateMachinePersistConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    /**
     * 注入RedisStateMachinePersister对象
     */
    @Bean(name = "taskStateMachineRedisPersister")
    public RedisStateMachinePersister<TaskState, TaskEvent> taskStateMachineRedisPersister() {
        return new RedisStateMachinePersister<>(taskStateMachineRedisPersist());
    }

    /**
     * 通过redisConnectionFactory创建StateMachinePersist
     */
    public StateMachinePersist<TaskState, TaskEvent, String> taskStateMachineRedisPersist() {
        RedisStateMachineContextRepository<TaskState, TaskEvent> repository = new RedisStateMachineContextRepository<>(redisConnectionFactory);
        return new RepositoryStateMachinePersist<>(repository);
    }

    @Bean(name = "jobStateMachineRedisPersister")
    public RedisStateMachinePersister<JobState, JobEvent> jobStateMachineRedisPersister() {
        return new RedisStateMachinePersister<>(jobStateMachineRedisPersist());
    }

    public StateMachinePersist<JobState, JobEvent, String> jobStateMachineRedisPersist() {
        RedisStateMachineContextRepository<JobState, JobEvent> repository = new RedisStateMachineContextRepository<>(redisConnectionFactory);
        return new RepositoryStateMachinePersist<>(repository);
    }

}

