aboutsummaryrefslogtreecommitdiff
path: root/Week14 Route 66/src/com/camilstaps/route66/Crossing.java
blob: eba5bfe04c4f79bb28109d1d278d9c14ec51cab6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 * Copyright (c) 2015 Camil Staps
 */
package com.camilstaps.route66;

import OO14route66.Direction;
import OO14route66.Model;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author camilstaps
 */
public class Crossing {
    
    private final Model model;
    private Direction allowed;
    private boolean waiting = false;
    private int requests = 0;
    
    public Crossing(Model model, Direction allowed) {
        this.model = model;
        this.allowed = allowed;
    }
    
    public Direction getAllowed() {
        return allowed;
    }
    
    public synchronized void doSwitch() {
        waiting = true;
        while (!model.isNoCarsOnCrossing());
        System.err.println("Switching");
        if (allowed == Direction.East || allowed == Direction.West) {
            allowed = Direction.North;
        } else {
            allowed = Direction.East;
        }
        requests = 0;
        System.err.println("Switched to " + allowed);
        waiting = false;
        //notifyAll();
    }
    
    public boolean isAllowed(Direction direction) {
        return !waiting && (direction == allowed || Direction.opposite(direction) == allowed);
    }
    
    public boolean doRequest() {
        //if (++requests >= 2) {
        if (waiting) {
            return false;
        }
            doSwitch();
            return true;
        //}
        //return false;
    }
    
}