import json
import time
import schedule

from server.consts import LAKE_RELATIONS_PATH
from ModelFromNVE.icemodellingscripts.getIceThicknessLakes import update_data
from map_handler.update_measurements import update_measurements_handler


def update_all_measurements(lake_names: list):
    """Loops through all lake names and calls get_measurements() on each lake"""
    for lake in lake_names:
        # NB dates are hard coded to january for demonstration. For deployment, simply remove the date parameters.
        from_date = "2024-01-10"
        to_date = "2024-01-20"

        update_data(from_date, to_date, lake_name=lake_names,
                    sub_divs_folder = LAKE_RELATIONS_PATH + lake_names + '_centers.txt', update_all_bboxes=True)

        update_measurements_handler(None, lake)


def update_scheduler():
    """Schedules the updating of all maps every three days"""
    print("Updating all lake data. This may take some time...")

    # Parse all lake names to a list. Set encoding to utf-8 to retain scandinavian characters
    with open(LAKE_RELATIONS_PATH + 'all_lake_names.json', 'r', encoding='utf-8') as file:
        lake_names = json.load(file)

    # Run update_all_measurements on startup
    update_all_measurements(lake_names)

    # Schedule the updating of all maps every three days
    schedule.every(3).days.do(update_all_measurements(lake_names))

    # Keep scheduler running indefinitely
    while True:
        schedule.run_pending()
        time.sleep(1)