import json


class RouteReader:
    def __init__(self, route_path):
        """
        Class for reading Json route generated by BikeRouteGen.
        Args:
            route_path: address where the route is saved.
        """
        self.route_path = route_path

    def read(self):
        """
        Read the route from the file.
        Returns:
            route: route dictionary
        """
        route = None
        with open(self.route_path) as f:
            json_route = json.load(f)
            route = self.merge_dicts([*json_route["sub_routes"]])
            route["route_render"] = json_route["route_render"]

        return route

    def merge_dicts(self, dict_list):
        """
        Helper method that merges dictionaries.
        Args:
            dict_list:

        Returns:
            merged_dict: merged dictionary
        """
        merged_dict = {}
        for key in dict_list[0].keys():  # Assuming all dictionaries have the same keys
            if isinstance(dict_list[0][key], list):
                merged_dict[key] = [item for d in dict_list for item in d[key]]
            elif isinstance(dict_list[0][key], dict):
                # Recursive call to handle nested dictionaries
                nested_dicts = [d[key] for d in dict_list]
                merged_dict[key] = self.merge_dicts(nested_dicts)
            else:
                # For non-list, non-dict types, you can choose how to handle them.
                # Here, I'm taking the value from the first dictionary for simplicity.
                merged_dict[key] = dict_list[0][key]
        return merged_dict

    def get_polyline(self, route):
        """
        Helper method that returns the polyline of the route.
        Args:
            route: route generated by BikeRouteGen and processed by read() method.

        Returns:
            polyline: list of tuples with the latitude and longitude of the route.
        """
        polyline = []
        for point in route["route_render"]:
            polyline.append((point["lat"], point["lon"]))
        return polyline
