import random


def simulation(data, num_substations, probabilities, iterations):
    """
    This function runs the infrastructure simulation.

    For a given number of nodes we wish to knock-out, quantify the potential
    population disruption.

    Parameters
    ----------
    data : list of dicts
        Contains all electricity substation information.
    num_substations : list
        The number of electricity substation nodes we wish to select for each scenario.
    probabilities : list
        Contains the cumulative probabilities we wish to use.
    iterations : int
        The number of Monte Carlo draws we wish to undertake.

    Returns
    -------
    output : list of dicts
        Contains all generated results.

    """
    random.seed(42)

    output = []

    for nodes in num_substations:

        for i in range(0, iterations):

            substation_ids = []

            while len(substation_ids) < nodes:

                n = random.randint(0, len(data))

                if not n in substation_ids:
                    substation_ids.append(n)

            substation_asset_ids = []

            population = 0

            for key, value in data.items():

                if key in substation_ids:
                    substation_asset_ids.append(value['id'])
                    population += value['population']

            output.append({
                'nodes': nodes,
                'iteration': i,
                'population': population,
                'substation_ids': substation_ids,
                'substation_asset_ids': substation_asset_ids,
            })

    return output