package de.renew.net.inscription.arc;

import de.renew.engine.common.SimulatorEventLogger;
import de.renew.engine.events.Untesting;
import de.renew.engine.searcher.LateExecutable;
import de.renew.simulatorontology.simulation.StepIdentifier;
import de.renew.util.Lock;

class UntestArcExecutable implements LateExecutable {
    // Here we store the test arc executable, whose action
    // we are supposed to undo. Untesting arbitrary tokens at
    // arbitrary times is not required.
    private final TestArcExecutable _tester;

    UntestArcExecutable(TestArcExecutable tester) {
        _tester = tester;
    }

    @Override
    public int phase() {
        return OUTPUT;
    }

    // We can untest a token quickly.
    @Override
    public boolean isLong() {
        return false;
    }

    @Override
    public void execute(StepIdentifier stepIdentifier) {
        if (_tester.isTrace()) {
            // log activity on net level
            SimulatorEventLogger.log(
                stepIdentifier, new Untesting(_tester.getToken(), _tester.getPlaceInstance()),
                _tester.getPlaceInstance());
        }
        Lock lock = _tester.getPlaceInstance()._lock;
        lock.lock();
        try {
            _tester.getPlaceInstance().untestToken(_tester.getToken());
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void executeAfterException(StepIdentifier stepIdentifier, Throwable t) {
        // Do not keep tested tokens tested.
        execute(stepIdentifier);
    }
}