package vs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BallotBox {
    private static Map<String, Integer> votesUnsafe = new HashMap<>();
    private static Map<String, Integer> votesSafe = Collections
            .synchronizedMap(votesUnsafe);

    public static void vote(String choice) {
        synchronized (votesSafe) {
            var v = votesUnsafe.get(choice);
            if (v == null) {
                v = 0;
            }
            votesUnsafe.put(choice, v + 1);
        }
    }

    public static int votesNumber() {
        var sum = 0;
        synchronized (votesSafe) {
            for (var choice : votesUnsafe.entrySet()) {
                sum += choice.getValue();
            }
        }
        return sum;
    }

    public static int votes(String choice) {
        if (votesSafe.get(choice) == null) {
            return 0;
        } else {
            return votesUnsafe.get(choice);
        }
    }

    public static List<Vote> votes() {
        var listOfVotes = new ArrayList<Vote>();
        synchronized (votesSafe) {
            for (var choice : votesUnsafe.entrySet()) {
                listOfVotes.add(new Vote(choice.getKey(), choice.getValue()));
            }
        }
        return listOfVotes;
    }

    public static Vote cheat(String choice, int votes) {
        BallotBox.votesSafe.put(choice, votes);
        return new Vote(choice, votes);
    }

    public static Set<String> choices() {
        return votesSafe.keySet();
    }
}
