001package jmri.jmrit.blockboss; 002 003import jmri.*; 004import org.slf4j.Logger; 005import org.slf4j.LoggerFactory; 006 007import javax.annotation.Nonnull; 008import java.util.*; 009 010/** 011 * Provider for {@link BlockBossLogic} objects 012 * 013 * @author Paul Bender Copyright (C) 2020 014 */ 015public class BlockBossLogicProvider implements Disposable, InstanceManagerAutoDefault { 016 017 private final SignalHeadManager signalHeadManager; 018 private final Map<SignalHead,BlockBossLogic> headToBlockBossLogicMap; 019 020 public BlockBossLogicProvider() { 021 signalHeadManager = InstanceManager.getDefault(SignalHeadManager.class); 022 headToBlockBossLogicMap = new TreeMap<>(new jmri.util.NamedBeanComparator<SignalHead>()); 023 ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class); 024 if (cm != null) { 025 cm.registerConfig(this, jmri.Manager.BLOCKBOSS); 026 } 027 } 028 029 public BlockBossLogic provide(@Nonnull String signalName) { 030 SignalHead signalHead = signalHeadManager.getSignalHead(signalName); 031 if (signalHead == null) { 032 log.error("SignalHead {} doesn't exist, BlockBossLogic.getExisting(\"{}\") cannot continue", signalName, signalName); 033 throw new IllegalArgumentException("Requested signal head doesn't exist"); 034 } 035 return provide(signalHead); 036 } 037 038 public BlockBossLogic provide(@Nonnull SignalHead signalHead){ 039 if (signalHead == null) { 040 log.error("BlockBossLogic requested for null signal head."); 041 throw new IllegalArgumentException("BlockBossLogic Requested for null signal head."); 042 } 043 return headToBlockBossLogicMap.computeIfAbsent(signalHead,o -> new BlockBossLogic(o.getDisplayName())); 044 } 045 046 public void register(BlockBossLogic blockBossLogic){ 047 headToBlockBossLogicMap.put(blockBossLogic.driveSignal.getBean(),blockBossLogic); 048 } 049 050 public void remove(BlockBossLogic blockBossLogic){ 051 headToBlockBossLogicMap.remove(blockBossLogic.driveSignal.getBean(),blockBossLogic); 052 } 053 054 public Collection<BlockBossLogic> provideAll(){ 055 return headToBlockBossLogicMap.values(); 056 } 057 058 @Override 059 public void dispose(){ 060 for (BlockBossLogic b : headToBlockBossLogicMap.values()) { 061 b.stop(); 062 } 063 headToBlockBossLogicMap.clear(); 064 } 065 066 private static final Logger log = LoggerFactory.getLogger(BlockBossLogicProvider.class); 067 068}