# %%


import googlemaps

from gmplot import GoogleMapPlotter
import json
import pandas as pd
import ast
import random
import itertools
import time



from math import sqrt, sin, cos, atan2, pi



gmaps = googlemaps.Client(key='AIzaSyB76EhR4OqjdXHQUiTkHZC0Svx_7cPGqyU')


def degreesToRadians(degrees):
    """ Convert degrees to radians """
    return degrees * pi / 180


def distanceInKmByGPS(lat1, lon1, lat2, lon2):
    """ Calculate the distance between two points in km """
    earthRadiusKm = 6371
    dLat = degreesToRadians(lat2 - lat1)
    dLon = degreesToRadians(lon2 - lon1)
    lat1 = degreesToRadians(lat1)
    lat2 = degreesToRadians(lat2)
    a = sin(dLat / 2) * sin(dLat / 2) + sin(dLon / 2) * \
        sin(dLon / 2) * cos(lat1) * cos(lat2)
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    return int(earthRadiusKm * c)

# %%

with open('data/sachsen.json', 'r', encoding='utf-8') as f:
    competitions = json.load(f)
    
competitions = {ast.literal_eval(k): v for k, v in competitions.items()}

competition_details = {}
color = None

teams_in_competition = {}

for staffel ,attr in competitions.items():
    if (staffel[0],staffel[1]) not in competition_details:
        competition_details[(staffel[0],staffel[1])] = {
            'nStaffeln': 1,
            'nTeams': 0,
            'distances': {},
            'teams': []
        }
    else:
        competition_details[(staffel[0],staffel[1])]['nStaffeln'] += 1
        
        
        
    for team in attr['teams']:
        if team['MANNSCHAFT'] not in competition_details[(staffel[0],staffel[1])]['teams']:
            competition_details[(staffel[0],staffel[1])]['teams'].append(team)
                
csv_file = 'data/distances.csv'


f = open(csv_file, 'w')
f.write('art,klasse,team1,team2,road_distance,road_duration,flight_distance\n')

                    
for competition, details in competition_details.items():
    print(f"Calculating distances for {competition}")
    for team1 in details['teams']:
        details['distances'][team1['MANNSCHAFT']] = {}
        for team2 in details['teams']:
            if team1 != team2:
                start = team1
                end = team2
                c = 0
                while(c <= 1):
                    try:
                        road_distance = gmaps.distance_matrix((start['LATITUDE'],start['LONGITUDE']),(end['LATITUDE'],end['LONGITUDE']))['rows'][0]['elements'][0]['distance']['value']
                        road_duration = gmaps.distance_matrix((start['LATITUDE'],start['LONGITUDE']),(end['LATITUDE'],end['LONGITUDE']))['rows'][0]['elements'][0]['duration']['value']
                        c = 3
                    except:
                        road_distance = 0
                        road_duration = 0
                        print(f"Error with {team1['MANNSCHAFT']} and {team2['MANNSCHAFT']}")
                        time.sleep(3)
                        c += 1
                road_distance = round(road_distance*0.001)
                road_duration = round(road_duration*0.016666)
                
                flight_distance = distanceInKmByGPS(team1['LATITUDE'], team1['LONGITUDE'], team2['LATITUDE'], team2['LONGITUDE'])
                
                # details['distances'][team1['MANNSCHAFT']][team2['MANNSCHAFT']] = {
                #     'road_distance': road_distance,
                #     'road_duration': road_duration,
                #     'flight_distance': flight_distance
                # }
                # print(f"Distance between {team1['MANNSCHAFT']} and {team2['MANNSCHAFT']} calculated", details['distances'][team1['MANNSCHAFT']][team2['MANNSCHAFT']])
                f.write(f"{competition[0]},{competition[1]},{team1['MANNSCHAFT']},{team2['MANNSCHAFT']},{road_distance},{road_duration},{flight_distance}\n")


f.close()

# matrix_str_keys = {str(k): v for k, v in competition_details.items()}
# with open('data/sachsen_matrix.json', 'w', encoding='utf-8') as f:
#     json.dump(matrix_str_keys, f, ensure_ascii=False, indent=4, default=str)
# %%
# %%
