import csv
import folium
from frictionless import Resource, Schema, validate

# Validates the given CSV file against a frictionless schema
def validate_csv_with_schema(file_path, schema_path):
    schema = Schema(schema_path)
    resource = Resource(file_path, schema=schema)
    report = validate(resource)
    
    if report.valid:
        print("CSV file validated using frictionless schema")
    else:
        print("Unable to validate CSV file:")
        for error in report.flatten(["rowPosition", "fieldPosition", "code", "message"]):
            print(f"Row {error['rowPosition']}, Column {error['fieldPosition']}: {error['message']}")

# Create OpenStreetMap overlay using folium library
def show_coordinates_on_map(file_path):
    # Set the center to the city of Nortorf (which is the center of Schleswig-Holstein
    # according to Google):
    m = folium.Map(location=[54.16995, 9.85516], zoom_start=6)

    # Read coordinates and description from CSV file
    with open(file_path, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile, delimiter = ";")
        for row in reader:
            #print(row.keys())
            lon = float(row['geogrLaenge'])
            lat = float(row['geogrBreite'])
            #name = row.get('name', 'pegelName')
            name = row['pegelName']
            folium.Marker([lat, lon], popup=name).add_to(m)

    # Save map
    map_file = 'output.htm'
    m.save(map_file)
    print(f"Map has been saved as: '{map_file}'")

# Main program
csv_file = 'pegel.csv'
schema_file = 'frictionless-description.json'

# Step 1: Validate CSV against frictionless schema
validate_csv_with_schema(csv_file, schema_file)

# Step 2: Create OpenStreetMap overlay
show_coordinates_on_map(csv_file)