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 HashMap<>();
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    public void dispose(){
059        for (BlockBossLogic b : headToBlockBossLogicMap.values()) {
060            b.stop();
061        }
062        headToBlockBossLogicMap.clear();
063    }
064
065    private static final Logger log = LoggerFactory.getLogger(BlockBossLogicProvider.class);
066
067}