001/*
002 *  @author Gregory J. Bedlek Copyright (C) 2018, 2019
003 */
004package jmri.jmrit.ctc;
005
006import java.util.ArrayList;
007import jmri.InstanceManager;
008import jmri.SignalMast;
009import jmri.SignalMastLogic;
010import jmri.SignalMastLogicManager;
011import jmri.Turnout;
012import jmri.jmrit.ctc.ctcserialdata.OtherData;
013
014public class IndicationLockingSignals {
015    private final ArrayList<NBHSignal> _mListOfSignals;
016    private final Turnout turnout;
017    private final OtherData.SIGNAL_SYSTEM_TYPE signalType;
018
019    public IndicationLockingSignals(String userIdentifier, ArrayList<NBHSignal> signals, NBHTurnout nbhTurnout,
020            OtherData.SIGNAL_SYSTEM_TYPE signalSystemType) {
021        turnout = nbhTurnout.getBean();
022        signalType = signalSystemType;
023        _mListOfSignals = signals;
024    }
025
026    public void removeAllListeners() {}   // None done.
027
028    public boolean routeClearedAcross() {
029        if (signalType == OtherData.SIGNAL_SYSTEM_TYPE.SIGNALHEAD) {
030            return checkSignalHeads();
031        } else if (signalType == OtherData.SIGNAL_SYSTEM_TYPE.SIGNALMAST) {
032            return checkSignalMasts();
033        }
034        return false;
035    }
036
037    private boolean checkSignalHeads() {
038        for (NBHSignal signal : _mListOfSignals) {
039            if (!signal.isDanger()) return true;
040        }
041        return false;
042    }
043
044    private boolean checkSignalMasts() {
045        for (NBHSignal signal : _mListOfSignals) {
046            if (checkMast((SignalMast) signal.getBean(), turnout)) return true;
047        }
048        return false;
049    }
050
051    private boolean checkMast(SignalMast mast, Turnout turnout) {
052        if (mast.getHeld()) return false;
053
054        // Get the SML for the mast and check for an active destination
055        SignalMastLogic sml = InstanceManager.getDefault(SignalMastLogicManager.class).getSignalMastLogic(mast);
056        // It is possible if the user put in (for example) a "bumper signal" (end of track signal)
057        // either accidentally or purposefully for there to be no logic at all.
058        if (sml == null) return false;
059        SignalMast activeDest = sml.getActiveDestination();
060        if (activeDest == null) return false;
061
062        // Check the auto turnouts for a match
063        for (Turnout autoTurnout : sml.getAutoTurnouts(activeDest)) {
064            if (autoTurnout == turnout) return true;
065        }
066
067        // Check the manual turnouts for a match
068        for (Turnout manualTurnout : sml.getTurnouts(activeDest)) {
069            if (manualTurnout == turnout) return true;
070        }
071
072        return false;
073    }
074}