package de.verteiltearchitekturen.election;

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> votes = Collections
            .synchronizedMap(new HashMap<>());

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

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

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

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

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

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