import random


def generate_trip_data(num_existing_trips, num_trips, num_destinations):   
    """Generates a list of tripData to be inserted into the database.
    
    Keyword arguments:
    num_existing_trips -- number of trips in the evolutions
    num_trips -- number of trips being created by the script
    num_destinations -- number of destinations being created by the script
    
    
    Returns:
    trip_data -- a list of strings to be added to the SQL script
    trip_destination_data -- a dictionary mapping a trip id to all the
                             destinations visited along the trip
    """
    
    trip_data = ["INSERT IGNORE INTO TripData (trip_id, position, destination_id) VALUES\n"]
    trip_data_template = "({0}, {1}, {2}),\n"
    
    trip_destination_data = {}
    
    for i in range(num_trips):
        trip_id = num_existing_trips + i + 1 # +1 because SQL ids start from 1
        
        used_destinations = set() # The destinations this trip has been given
        
        for j in range(random.randint(2, 4)):
            position = j + 1 # +1 because SQL ids start from 1
            destination_id = random.randint(1, num_destinations)
            
            # Ensure that each destination is unique
            while destination_id in used_destinations:
                destination_id = random.randint(1, num_destinations)
                
            used_destinations.add(destination_id)
            
            trip_data.append(trip_data_template.format(trip_id, position, destination_id))
            trip_destination_data.setdefault(trip_id, []).append(destination_id)
    
    # Make the last commas semi-codes instead, with a newline for formatting        
    trip_data[-1] = trip_data[-1][:-2] + ";\n"
    return trip_data, trip_destination_data