package cuckoomodel;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Network {

	private final List<Interval> intervals = new ArrayList<Interval>(); 

	private final Random rand = new Random();
	
	
	
	
	
	public Network() {}
	
	public void init(int nrOfIntervals) {
		intervals.clear();
		for (int i= 0 ; i < nrOfIntervals; i++) {
			intervals.add(new Interval(this));
		}
	}
	
	public void addPeers(int number, boolean evil) {
		for (int i=0; i < number; i++) {
			new Node(evil).join(getRandomInterval(), true);
		}
	}
	
	public Interval getRandomInterval() {
		return intervals.get(rand.nextInt(intervals.size()));
	}
	
	/**
	 * @return the intervals
	 */
	public List<Interval> getIntervals() {
		return intervals;
	}
	
	public Attack rejoinAttack(int peers, int intervalsToConquer) {
		return new Attack(peers,intervalsToConquer,this);
	}
	
	
	public static class Attack {
		private List<Node> rejoinAttackPeers = new ArrayList<Node>();
		private final int intervalsToConquer;
		private final Network net;
		
		private Attack(int peers, int intervals, Network n) {
			this.net = n;
			this.intervalsToConquer = intervals;
			for (int i=0; i  < peers; i++) {
				rejoinAttackPeers.add(new Node(true));
			}
		}
		
		/**
		 * 
		 * @return if the attack was successful
		 */
		public boolean attack() {
			for (Node n: rejoinAttackPeers) {
				n.join( net.getRandomInterval() ,true);
				if (attackSuccess()) {
					return true;
				}
			}
			return false;
		}
		
		private boolean attackSuccess() {
			for (int i=0; i < intervalsToConquer ; i++) {
				if (!net.intervals.get(i).isCompromised()) {
					return false;
				}
			}
			return true;
		}
	}
	
	
	

}

