import csv

def outputter(mode, criterion, tsp_route, graph, speed, cost_per_km, co2_per_km):

    if mode == "car":
        print("Totals for route with car:")
    elif mode == "bicycle":
        print("Totals for route with bicycle:")
    elif mode == "walking":
        print("Totals for route with walking:")


    print("Delivery Route:", " -> ".join(tsp_route))

    total_distance = 0


    fieldnames = ['Stop', 'Distance from last stop', 'Total distance', 'ETA', 'cost','CO2']
    with open('route.csv', 'w', newline='') as csvfile:
        csvfile.truncate(0)
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        output_row = {'Stop': '', 'Distance from last stop':'','Total distance':'', 'ETA': '', 'cost': '', 'CO2':''}

        total_distance = 0
        total_time = 0
        total_cost = 0
        total_co2 = 0

        for i in range((len(tsp_route))):
            if i == 0:
                output_row['Stop'] = tsp_route[0]
                output_row['Distance from last stop'] = "0"
                output_row['Total distance'] = "0"
                output_row['ETA'] = "0"
                output_row['cost'] = "0"
                output_row['CO2'] = "0"
                writer.writerow(output_row)
                continue
            output_row['Stop'] = tsp_route[i]
            distance_from_last_stop = graph[tsp_route[i-1]][tsp_route[i]]["distance"]
            output_row['Distance from last stop'] = str(distance_from_last_stop)
            total_distance += distance_from_last_stop
            output_row['Total distance'] = str(total_distance)
            total_time = total_distance / speed
            output_row['ETA'] = str(total_time)
            total_cost = total_distance * cost_per_km
            output_row['cost'] = str(total_cost)
            total_co2 = total_distance * co2_per_km
            output_row['CO2'] = str(total_co2)

            writer.writerow(output_row)

    #for i in range(len(tsp_route) - 1):
    #    total_distance += graph[tsp_route[i]][tsp_route[i + 1]]["distance"]

    print(f"Total Distance: {total_distance:.2f} km")


    if criterion == "1":
        print(f"Total Time: {total_time:.2f} hours")
    elif criterion == "2":
        print(f"Total cost: {total_cost:.2f} NOK")
    elif criterion == "3":
        print(f"Total CO2: {total_co2:.2f} grams of CO2")
    print("Check route.csv within the output folder for more details")

