import csv

# Problem to solve: indices of nodes. Not always starting at 1 with a step of 1 (import from OSM). 
# Do the same for edges.

filename_nodes_csv = "nodes.csv"
filename_edges_csv = "edges.csv"
filename_users_csv = "users.csv"

mapping_nodes = {}
new_nodes = [["Node index", "Node name"]]
new_edges = [["Edge index", "Origin node index", "Destination node index", "Length (km)"]]
new_users = [["Person index", "Person is driver (binary)", "Driver number of seats", "Driver maximum path length (km)", "Person origin node index", "Person destination node index"]]

# Deal with the nodes. 
with open(filename_nodes_csv, "r") as f: 
    reader_nodes = csv.reader(f, delimiter=",")
    next(reader_nodes)
    
    i = 1
    for line_node in reader_nodes: 
        new_nodes.append([i, line_node[1]])
        mapping_nodes[int(line_node[0])] = i
        i += 1
    
with open(filename_nodes_csv, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(new_nodes)

# Deal with the edges. 
with open(filename_edges_csv, "r") as f: 
    edges_file = csv.reader(f, delimiter=",")
    next(edges_file)
    
    i = 1
    for line_edge in edges_file: 
        line_edge[0] = i
        line_edge[1] = mapping_nodes[int(line_edge[1])]
        line_edge[2] = mapping_nodes[int(line_edge[2])]
        new_edges.append(line_edge)
        i += 1
    
with open(filename_edges_csv, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(new_edges)

# Deal with the users. 
with open(filename_users_csv, "r") as f: 
    users_file = csv.reader(f, delimiter=",")
    next(users_file)
    for line_user in users_file: 
        line_user[4] = mapping_nodes[int(line_user[4])]
        line_user[5] = mapping_nodes[int(line_user[5])]
        new_users.append(line_user)
    
with open(filename_users_csv, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(new_users)
            
            