package in.ocsf.these.days.app.service;/* kpmy 19.02.2017 */ import com.pengrad.telegrambot.model.Update; import in.ocsf.these.days.app.messaging.UpdateHelper; import in.ocsf.these.days.app.object.Chat; import in.ocsf.these.days.app.object.User; import in.ocsf.these.days.app.repo.ChatRepository; import in.ocsf.these.days.app.repo.UserRepository; import in.ocsf.these.days.app.state.IChat; import in.ocsf.these.days.app.state.StateService; import in.ocsf.these.days.app.state.account.Accounted; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.statemachine.StateMachine; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UpdateService { private final Logger log = Logger.getLogger(getClass()); @Autowired private ApplicationContext context; @Autowired private UserRepository userRepo; @Autowired private StateService stateService; @Autowired private ChatRepository chatRepo; @Autowired private CommandService commandService; @Autowired private Accounted accounted; private void handleUpdate(UpdateHelper upd) { if (!upd.hasText()) throw new RuntimeException(); User user = User.fromUser(upd.getUser()); user = Optional.ofNullable(userRepo.findOne(user.getId())).orElse(user); StateMachine state = stateService.getStateFor(user); stateService.put(state, IChat.USER, user.getId()); stateService.put(state, upd); if (state.getState() == null) { userRepo.save(user); chatRepo.findByUserIdAndThenClose(user.getId()); state.start(); stateService.setStateFor(user, state); userRepo.save(user); } if (upd.isCommand()) commandService.handle(state); else { Optional chat0 = chatRepo.findByUserIdAndStateThenActualize(user.getId()); chat0.ifPresent(c -> { StateMachine chatState = stateService.getChatStateFor(c); stateService.put(chatState, upd); stateService.put(chatState, IChat.CHAT, c.getId()); IChat chat = context.getBean(c.getType().getBean()); chat.handle(chatState); }); if (!chat0.isPresent()) accounted.handle(state); } } public void handleUpdate(Update upd) { UpdateHelper helper = UpdateHelper.from(upd); if (!helper.isEdit()) handleUpdate(helper); } }